用ggplot实现双坐标轴图形

来源:互联网 发布:霸道总裁小说知乎 编辑:程序博客网 时间:2024/06/05 05:45
如何完成双坐标轴图(如下)
R代码
library(ggplot2)library(gtable)library(grid)setwd("C:\\Users\\msy\\Documents\\work\\年度")shuaxin<-read.csv("总体test.csv",stringsAsFactors = FALSE)shuaxinp1<-ggplot(shuaxin,aes(x=as.factor(month),cash))+geom_bar(stat="identity",fill="#BED742")+theme_bw()+  labs(x="",y="")+  coord_cartesian(ylim=c(0,1400000))+  ggtitle("Draw by 小酥饼maomao")+  geom_text(aes(label=round(cash/10000,1)),vjust=1.5,colour="white",size=4)+  theme_bw()+  theme(axis.title.x=element_blank(),        axis.title.y=element_blank(),        #axis.text.x=element_text(angle=30,hjust=1,vjust=1),        plot.title=element_text(size=23,face="bold",vjust=1),        panel.border=element_blank(),        panel.grid.major.x=element_blank(),        panel.grid.minor.x=element_blank(),        panel.grid.major.y=element_blank(),        panel.grid.minor.y=element_blank(),        legend.position="none",        axis.line=element_line(color="gray",size=1))p2<-ggplot(shuaxin,aes(x=month,ratio))+geom_line(stat="identity",colour="#FFF400",size=1)+  theme_bw()+  coord_cartesian(ylim=c(-0.8,0.2))+  geom_text(aes(label=paste(round(ratio*100,1),"%",sep="")),vjust=-0.5,size=4)+  theme(axis.title.x=element_blank(),        axis.title.y=element_blank(),        #axis.text.x=element_text(angle=30,hjust=1,vjust=1),        plot.title=element_text(size=23,face="bold",vjust=1),        panel.border=element_blank(),        panel.grid.major.x=element_blank(),        panel.grid.minor.x=element_blank(),        panel.grid.major.y=element_blank(),        panel.grid.minor.y=element_blank(),        legend.position="none",        axis.line=element_line(color="gray",size=1),        panel.background = element_rect(fill = NA))g1 <- ggplot_gtable(ggplot_build(p1))g2 <- ggplot_gtable(ggplot_build(p2))# overlap the panel of 2nd plot on that of 1st plotpp <- c(subset(g1$layout, name == "panel", se = t:r))g <- gtable_add_grob(g1, g2$grobs[[which(g2$layout$name == "panel")]], pp$t,                     pp$l, pp$b, pp$l)# axis tweaksia <- which(g2$layout$name == "axis-l")ga <- g2$grobs[[ia]]ax <- ga$children[[2]]ax$widths <- rev(ax$widths)ax$grobs <- rev(ax$grobs)ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) +0.1)g <- gtable_add_grob(g, ax, pp$t, length(g$widths) +0.1, pp$b)ia <- which(g2$layout$name == "ylab")ga <- g2$grobs[[ia]]ga$rot <- 270g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) +0.1)g <- gtable_add_grob(g, ga, pp$t, length(g$widths) +0.1 , pp$b)# draw itgrid.draw(g)


0 0
原创粉丝点击