用ggplot实现双坐标轴图形

时间:2021-05-23 15:00:13
如何完成双坐标轴图(如下)
用ggplot实现双坐标轴图形
R代码
library(ggplot2)
library(gtable)
library(grid)
setwd("C:\\Users\\msy\\Documents\\work\\年度")
shuaxin<-read.csv("总体test.csv",stringsAsFactors = FALSE)
shuaxin

p1<-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 plot
pp <- 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 tweaks
ia <- 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 <- 270
g <- 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 it

grid.draw(g)