ggplot2 因子变量 x 轴断点 geom_area

3
我一直在尝试使用离散的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")

enter image description here

dat$year <- factor(dat$year)

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

enter image description here

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   

面积图如何适用于分类数据?如果您不喜欢看到小数,也许最好使用 scale_x_continuous 控制轴? - Gopala
@Gopola,我觉得这很合理。如上所述,我需要在x轴上显示财政年度的时间。另一个例子可能是年份-季度(2013q3、2013q4、2014q1),在这种情况下,连续的比例尺并不太有意义。无论如何,因素被存储为带标签的整数,因此我期望面积图能够毫无问题地绘制x轴。 - r.bot
区域图表展示连续变量的趋势。因此,您需要使用可以在连续比例尺上表示的类型。调整比例尺是一个不同的问题,这是我建议的方法,下面的答案也使用了这种方法。 - Gopala
1个回答

7
只需要添加换行符,无需将其作为因素。
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"))

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接