我尝试在ggplot中绘制一个具有两个Y轴的折线图。然而,我现在不能制作与第二轴对应的线-它只会根据主轴绘制。下面是dataframe的代码:
df <- data.frame(
type = c("A", "B", "C", "D"),
prop1 = c(0.31, 0.12, 0.55, 0.02),
prop2 = c(0.16, 0.22, 0.15, 0.22)
)
df$type <- factor(df$type,
levels = c("D", "B", "A", "C")) #to reorder the plot
现在,左边的Y轴应该对应于prop 1,而右边的Y轴应该对应于prop 2。我的代码如下:
ggplot(df) +
aes(x = type) +
geom_point(aes(y = prop1), size = 2) +
geom_line(aes(y = prop1), size = 1, group = 1) +
geom_point(aes(y = prop2), size = 2, shape = 15) +
geom_line(aes(y = prop2), size = 1, group = 1) +
theme_bw() +
labs(x = "") +
scale_y_continuous(name = "prop1\n",
breaks = seq(0,0.6,0.1),
limits = c(0,0.6),
labels = function(x) paste0(x * 100, "%"),
sec.axis = sec_axis(~., name = "prop2"))
此代码绘制如下内容:
蓝线(prop 2)应该扩展到对应于右Y轴(例如,限制为[0.1,0.25])。问题是该线仍然是根据左Y轴绘制的。
所需的图将具有蓝线,该蓝线具有更大的下降,因为次轴(右)中的极限小于主轴(左)中的极限。
我该怎么解决这个问题?谢谢!
1条答案
按热度按时间svmlkihl1#
一种方法可以是使用系数: