本文介绍了在ggplot2中合并条形图和折线图(双轴)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我在 Excel 中制作了 double-y-axis 图表。在Excel中只需要基本技能。我想要做的是使用 R 中的 ggplot2 库来复制此图表。 b $ b 我已经完成了这项工作,但是我需要绘制Response 2nd-y-axis 。 附上可重复使用的代码: #数据生成年份响应费率 df< - data.frame(Year,Response,Rate) #Chart library(ggplot2) ggplot(df)+ geom_bar(aes(x = Year,y = Response),stat =identity,fill =tan1,color =sienna3)+ geom_line (aes(x = Year,y = Rate),stat =identity)+ geom_text(aes(label = Rate,x = Year,y = Rate),color =black)+ geom_text(aes(label = Response,x = Year,y = 0.9 * Response),color =black) Rate * max(df $ Response) Rate > c $ c>并修改响应文本的 0.9 比例。其次,通过 scale_y_continuous(sec.axis = ...): ggplot(df) + geom_bar(aes(x = Year,y = Response),stat =identity,fill =tan1,color =sienna3)+ geom_line(aes(x = Year,y = Rate * max(df $ Response)),stat =identity)+ geom_text(aes(label = Rate,x = Year,y = Rate * max(df $ Response)),color =black )+ geom_text(aes(label = Response,x = Year,y = 0.95 * Response),color =black)+ scale_y_continuous(sec.axis = sec_axis(〜。/ max df $ Response))) 其中:b / b $ b I have double-y-axis chart made in Excel. In Excel it requires only basic skills. What I'd like to do is to replicate this chart using the ggplot2 library in R.I have already done this, but I need to plot Response on 2nd-y-axis.I enclose reproducible code I've used:#Data generationYear <- c(2014, 2015, 2016)Response <- c(1000, 1100, 1200)Rate <- c(0.75, 0.42, 0.80)df <- data.frame(Year, Response, Rate)#Chartlibrary(ggplot2)ggplot(df) + geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+ geom_line(aes(x=Year, y=Rate),stat="identity")+ geom_text(aes(label=Rate, x=Year, y=Rate), colour="black")+ geom_text(aes(label=Response, x=Year, y=0.9*Response), colour="black") 解决方案 First, scale Rate by Rate*max(df$Response) and modify the 0.9 scale of Response text.Second, include a second axis via scale_y_continuous(sec.axis=...):ggplot(df) + geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+ geom_line(aes(x=Year, y=Rate*max(df$Response)),stat="identity")+ geom_text(aes(label=Rate, x=Year, y=Rate*max(df$Response)), colour="black")+ geom_text(aes(label=Response, x=Year, y=0.95*Response), colour="black")+ scale_y_continuous(sec.axis = sec_axis(~./max(df$Response)))Which yields: 这篇关于在ggplot2中合并条形图和折线图(双轴)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-24 18:20