簡體   English   中英

ggplot2因子x變量中斷geom_area

[英]ggplot2 factor x variable breaks geom_area

我一直在嘗試生成具有離散x變量的堆積面積圖(因為我想顯示財務年度,即“ 2013/14”,而不是日歷年度)。 但是,將x軸變量變成一個因子會阻止在最終圖表中呈現幾何圖形。

有沒有解決的辦法?

library(ggplot2)

dat <- structure(list(year = c(13, 13, 14, 14, 15, 15), 
                      group_lvl = structure(c(1L, 2L, 1L, 2L, 1L, 2L), 
                                            .Label = c("a", "b"), class = "factor"), 
                      val = c(35, 65, 50, 50, 75, 25)), 
                 .Names = c("year", "group_lvl", "val"), row.names = c(NA, -6L), 
                 class = "data.frame")
dat
  year group_lvl val
1   13         a  35
2   13         b  65
3   14         a  50
4   14         b  50
5   15         a  75
6   15         b  25

ggplot(dat, aes(x = year, y = val)) + 
  geom_area(aes(fill = group_lvl), position = "stack")

在此處輸入圖片說明

dat$year <- factor(dat$year)

ggplot(dat, aes(x = year, y = val)) + 
  geom_area(aes(fill = group_lvl), position = "stack")

在此處輸入圖片說明

sessionInfo()
R version 3.3.0 (2016-05-03)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252   
[3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_2.1.0

loaded via a namespace (and not attached):
 [1] labeling_0.3     colorspace_1.2-6 scales_0.4.0     plyr_1.8.3       tools_3.3.0     
 [6] gtable_0.2.0     Rcpp_0.12.4      grid_3.3.0       digest_0.6.9     munsell_0.4.3   

只需添加休息時間,無需使其成為一個因素。

ggplot(dat, aes(x = year, y = val)) + 
  geom_area(aes(fill = group_lvl), position = "stack") + 
  scale_x_continuous(breaks=c(13,14,15),labels=c("2013","2014","2015"))

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM