双轴图,保持原始比例

问题描述 投票:0回答:0

到目前为止,这是我的GGPLOT

ggplot() + geom_bar(data= df, aes(x=year, y=production), stat = "identity") + geom_line(data= df, aes(x=year, y=price), color= "red") + labs(x="Year", y = "Production (Kg)") + scale_y_continuous(limits=c(95, 110), sec.axis = sec_axis(~ . *1 , name = "Price ($)")) + theme_bw()

谢谢你
	

要在GGPLOT中使用两个轴,您必须在一个方向上缩放数据并在AZIS上进行相反的缩放。以下代码使主要轴从0到12000,第二个轴从98到110,1/1000的主要轴范围。使用GEOM_BAR强制主轴以零启动。如果您为该轴使用了另一个底座,则可以扩展主轴以更清楚地显示生产的变化。 该代码不会在preprex中运行,但它在我的系统上运行,没有任何错误。

library(ggplot2) df <- data.frame(year= c(2000, 2001, 2002, 2003, 2004, 2005), price= c(100, 105, 102, 110, 98, 102), production= c(10000, 10500, 10250, 10300, 10450, 10320)) ggplot() + geom_bar(data= df, aes(x=year, y=production), stat = "identity") + geom_line(data= df, aes(x=year, y=(price-98)*1000), color= "red", linewidth = 1) + labs(x="Year", y = "Production (Kg)") + scale_y_continuous(limits = c(0,12000), sec.axis = sec_axis(~ ./1000+98 , name = "Price ($)")) + theme_bw() + theme(axis.text.y.right = element_text(color = "red"))
    

r ggplot2 graph tidyverse
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.