Subgroup axes ggplot2 and axis limits
关注至:
类似于Excel PivotChart
的子组轴ggplot2
ggplot2条形图的多个子组
我正在使用
数据:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | library(reshape2) library(ggplot2) library(grid) df=data.frame(year=rep(2010:2014,each=4), quarter=rep(c("Q1","Q2","Q3","Q4"),5), da=c(46,47,51,50,56.3,53.6,55.8,58.9,61.0,63,58.8,62.5,59.5,61.7,60.6,63.9,68.4,62.2,62,70.4)) df.m <- melt(data = df,id.vars = c("year","quarter")) g1 <- ggplot(data = df.m, aes(x = interaction(quarter,year), y = value, group = variable)) + geom_area(fill ="red")+ coord_cartesian(ylim = c(0, 75)) + annotate(geom ="text", x = seq_len(nrow(df)), y = -1.5, label = df$quarter, size = 2, color ="gray48") + annotate(geom ="text", x = 2.5 + 4 * (0:4), y = -3, label = unique(df$year), size = 3, color ="gray48") + theme_grey(base_size = 10)+ theme(line = element_line(size = 0.2), axis.title.x = element_blank(), axis.text.x = element_blank(), legend.position="none") #remove clipping of x axis labels g2 <- ggplot_gtable(ggplot_build(g1)) g2$layout$clip[g2$layout$name =="panel"] <-"off" grid.draw(g2) png(filename ="test.png",width = 14/2.54,height = 6/2.54, units ="in",res = 300) grid.draw(g2) dev.off() |
该图很好,并且轴标签符合要求。但是,一旦更改了y轴的界限,一切就搞砸了。
希望您有个主意,如何解决我的问题!
实际上,它确实在绘制您要的内容。选中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | library(reshape2) library(ggplot2) library(grid) df=data.frame(year=rep(2010:2014,each=4), quarter=rep(c("Q1","Q2","Q3","Q4"),5), da=c(46,47,51,50,56.3,53.6,55.8,58.9,61.0,63,58.8,62.5,59.5,61.7,60.6,63.9,68.4,62.2,62,70.4)) df.m <- melt(data = df,id.vars = c("year","quarter")) ymin <- 40 g1 <- ggplot(data = df.m, aes(x = interaction(quarter,year), ymax = value, group = variable)) + geom_ribbon(aes(ymin=ymin), fill ="red")+ coord_cartesian(ylim = c(ymin, 75)) + annotate(geom ="text", x = seq_len(nrow(df)), y = 37.5, label = df$quarter, size = 2, color ="gray48") + annotate(geom ="text", x = 2.5 + 4 * (0:4), y = 36.5, label = unique(df$year), size = 3, color ="gray48") + theme_grey(base_size = 10)+ theme(line = element_line(size = 0.2), axis.title.x = element_blank(), axis.text.x = element_blank(), legend.position="none", plot.margin = unit(c(1,1,3,1),"lines")) # The bottom margin is exaggerated a little # turn off clipping of the panel g2 <- ggplotGrob(g1) g2$layout$clip[g2$layout$name =="panel"] <-"off" grid.draw(g2) |