gpt4 book ai didi

r - geom_bar + geom_line : with different y-axis scale?

转载 作者:行者123 更新时间:2023-12-04 16:59:28 25 4
gpt4 key购买 nike

有什么方法可以像下面的图表一样用 geom_line 绘制 geom_bar 。

enter image description here

我想出了两个单独的图表。如何将它们分别与左右两个不同的轴组合在一起。

library(ggplot2)
temp = data.frame(Product=as.factor(c("A","B","C")),
N = c(17100,17533,6756),
n = c(5,13,11),
rate = c(0.0003,0.0007,0.0016),
labels = c(".03%",".07%",".16%"))

p1 = ggplot(data = temp, aes(x=Product,y=N))+
geom_bar(stat="identity",fill="#F8766D")+geom_text(aes(label=n,col="red",vjust=-0.5))+
theme(legend.position="none",axis.title.y=element_blank(),axis.text.x = element_text(angle = 90, hjust = 1))
p1
p2 = ggplot(data = temp,aes(x=Product,y=rate))+
geom_line(aes(group=1))+geom_text(aes(label=labels,col="red",vjust=0))+
theme(legend.position="none",axis.title.y=element_blank(),
axis.text.x = element_text(angle = 90, hjust = 0))+
xlab("Product")
p2

非常感谢。

最佳答案

现在,ggplot2添加了对辅助轴的支持(从 2.2.0 版开始),可以在单个 ggplot() 内用更少的代码创建这样的图形调用(没有堆叠多个图作为解决方法!)

ggplot(data = temp, aes(x = Product, y = N)) + #start plot by by plotting bars
geom_bar(stat = "identity") +
#plot line on same graph
# rate multiplied by 10000000 to get on same scale as bars
geom_line(data = temp, aes(x = Product, y = (rate)*10000000, group = 1),
inherit.aes = FALSE) +
#specify secondary axis
#apply inverse of above transformation to correctly scale secondary axis (/10000000)
scale_y_continuous(sec.axis = sec_axis(~./10000000, name = "rate"))

enter image description here

我知道这是一个有答案的旧问题,但想提供更新 - 由于包更新,有一个比接受的答案中的解决方案更简单的解决方案(这是当时最好的解决方案)。

关于r - geom_bar + geom_line : with different y-axis scale?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32090073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com