R语言 在双线ggplot上将比例更改为次轴

xbp102n0  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(76)

我尝试在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轴绘制的。
所需的图将具有蓝线,该蓝线具有更大的下降,因为次轴(右)中的极限小于主轴(左)中的极限。
我该怎么解决这个问题?谢谢!

svmlkihl

svmlkihl1#

一种方法可以是使用系数:

coeff <- 0.5

ggplot(df, aes(x = type)) +
  geom_point(aes(y = prop1), size = 2, color = "red")+
  geom_line(aes(y = prop1), size = 1, group = 1, color = "red") +
  geom_point(aes(y = prop2 / coeff), shape=23, fill="blue", size=2) +
  geom_line(aes(y = prop2 / coeff), size = 1, group = 1, color = "blue") +
  scale_y_continuous(
    name = "Prop1",
    sec.axis = sec_axis(~.*coeff, name = "Prop2")
  ) +
  xlab("\n My x label")+
  theme_bw(14)+
  theme(
    axis.title.y = element_text(color = "red", size=13, face="bold"),
    axis.title.y.right = element_text(color = "blue", size=13, face="bold"),
    axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1)
  ) +
  ggtitle("My title")

相关问题