[英]How can I plot with 2 different y-axes in R with ggplot2?
I have the next Data我有下一个数据
Fecha cases deaths countries pop2018 TotalCases TCP
1 2020-03-29 2546 260 United_Kingdom 66488991 17089 NA
2 2020-03-30 2433 209 United_Kingdom 66488991 19522 0.14237229
3 2020-03-31 2619 180 United_Kingdom 66488991 22141 0.13415634
4 2020-04-01 3009 381 United_Kingdom 66488991 25150 0.13590172
5 2020-04-02 4324 743 United_Kingdom 66488991 29474 0.17192843
6 2020-04-03 4244 389 United_Kingdom 66488991 33718 0.14399131
7 2020-04-04 4450 684 United_Kingdom 66488991 38168 0.13197699
8 2020-04-05 3735 708 United_Kingdom 66488991 41903 0.09785684
And the next plots接下来的情节
ggplot(data=Data_UK7, aes(x=Fecha, y=TCP)) +
geom_line(linetype = "twodash")+
geom_point()+
scale_x_date(date_breaks ="1 day")+
scale_y_continuous(breaks = seq(0,1,0.01))
ggplot(Data_UK7)+
geom_col(aes(x=Fecha,y=TotalCases))+
scale_x_date(date_breaks ="1 day")
It's possible to make a plot with this 2 graphs together?可以用这两张图一起制作 plot 吗? Something like this:
像这样的东西:
"All secondary axes must be based on a one-to-one transformation of the primary axes" per the ggplot2 docs for adding secondary y-axis via scale_y_continuous.根据 ggplot2 文档通过 scale_y_continuous 添加辅助 y 轴, “所有辅助轴必须基于主轴的一对一转换” 。
The TotalCases scale is about 200000 times (value around 40000) larger than the TCP scale (value around 0.15). TotalCases 比例大约是 TCP 比例(值大约 0.15)的 200000 倍(值大约 40000)。 You can play around with this number to get precise positioning, but something like this could work:
您可以使用这个数字来获得精确的定位,但这样的事情可能会起作用:
Data_UK7 <- read.table(text =
" Fecha cases deaths countries pop2018 TotalCases TCP
1 2020-03-29 2546 260 United_Kingdom 66488991 17089 NA
2 2020-03-30 2433 209 United_Kingdom 66488991 19522 0.14237229
3 2020-03-31 2619 180 United_Kingdom 66488991 22141 0.13415634
4 2020-04-01 3009 381 United_Kingdom 66488991 25150 0.13590172
5 2020-04-02 4324 743 United_Kingdom 66488991 29474 0.17192843
6 2020-04-03 4244 389 United_Kingdom 66488991 33718 0.14399131
7 2020-04-04 4450 684 United_Kingdom 66488991 38168 0.13197699
8 2020-04-05 3735 708 United_Kingdom 66488991 41903 0.09785684
",
header=TRUE)
Data_UK7$Fecha <- as.Date(Data_UK7$Fecha)
ggplot(Data_UK7)+
geom_col(aes(x=Fecha,y=TotalCases))+
scale_x_date(date_breaks ="1 day")+
geom_line(aes(x=Fecha, y=TCP*200000),linetype = "twodash")+
geom_point(aes(x=Fecha, y=TCP*200000))+
theme_classic()+
scale_y_continuous(sec.axis = sec_axis(~./200000, name = "TCP"))
The scaling needs to happen in both the specific geoms that will go on secondary axis (for this example the geom_point and geom_line with TCP in the aes) and also in scale_y_continuous.缩放需要在辅助轴上的 go 的特定几何中发生(对于本例,geom_point 和 geom_line 与 aes 中的 TCP)以及 scale_y_continuous。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.