ggplot2设置第二纵坐标轴

2022-04-07

使用scale_y_continuous函数中的sec_axis函数进行为ggplot2的作图,添加第二纵坐标轴。

How to add a secondary axis

library(ggplot2)

ggplot(data = iris,
       aes(x = seq_len(150))) +
  geom_line(aes(y = Petal.Width),
            size = 0.5) +
  xlab("Entry number") +
  ylab("Petal Width (cm)") +
  geom_line(aes(y = Petal.Length),
            size = 0.5,
            colour = "steelblue3") +
  scale_y_continuous(sec.axis =
                       sec_axis( ~ . ,
                                 name = "Petal Length (cm)"))

How to rotate the secondary axis

library(ggplot2)

ggplot(data = iris,
       aes(x = seq_len(150))) +
  geom_line(aes(y = Petal.Width),
            size = 0.5) +
  xlab("Entry number") +
  ylab("Petal Width (cm)") +
  geom_line(aes(y = Petal.Length),
            size = 0.5,
            colour = "steelblue3") +
  scale_y_continuous(sec.axis =
                       sec_axis( ~ . ,
                                 name = "Petal Length (cm)")) +
  theme( axis.title.y.right = element_text( angle = 90))

致谢

Rotate title of secondary y axis