【问题标题】:R: Changing the color of secondary axis tick labels with ggplotR:使用 ggplot 更改次轴刻度标签的颜色
【发布时间】:2021-07-28 19:01:35
【问题描述】:

我正在尝试生成与 ggplot 中的主刻度标签颜色不同的辅助轴刻度标签。

我有一个包含两组线和相应的不同 y 轴的图。如下面的最小示例所示,我已成功使每对线 + 轴标签对共享共同的颜色,以将它们与另一对区别开来。但是,我希望刻度标签也共享这些颜色。

直观的方法是使用 sec.axis 和 sec_axis,但它们似乎不能提供一种方法来区分辅助轴的刻度/标签的格式与主轴的格式。

谁有办法改变次轴刻度标签的颜色而不改变主轴的颜色?

library(ggplot2)

# Example data
df <- data.frame(y1 = 1:10,
           y2 = 2:11,
           x = 101:110)

# Example plot
df %>% ggplot2::ggplot() +
  geom_line(
    mapping = aes(x = x, y = y1),
    color = "black") +
  geom_point(
    mapping = aes(x = x, y = y1),
    color = "black") +
  geom_line(
    mapping = aes(x = x, y = y2),
    color = "red") +
  geom_point(
    mapping = aes(x = x, y = y2),
    color = "red") +
  scale_y_continuous(
    "Primary",
    sec.axis = sec_axis(~ ., name = "Secondary")
  ) +
  theme_bw() +
  theme(
    axis.title.y = element_text(color = "black"),
    axis.title.y.right = element_text(color = "red")
)

【问题讨论】:

    标签: r ggplot2 data-visualization visualization axis-labels


    【解决方案1】:

    您的代码很好,只需添加 theme():

    axis.text.y.right = element_text(colour = "red")
    

    像这样:

    df %>% ggplot2::ggplot() +
      geom_line(
        mapping = aes(x = x, y = y1),
        color = "black") +
      geom_point(
        mapping = aes(x = x, y = y1),
        color = "black") +
      geom_line(
        mapping = aes(x = x, y = y2),
        color = "red") +
      geom_point(
        mapping = aes(x = x, y = y2),
        color = "red") +
      scale_y_continuous(
        "Primary",
        sec.axis = sec_axis(~ ., name = "Secondary")
      ) +
      theme_bw() +
      theme(
        axis.title.y = element_text(color = "black"),
        axis.title.y.right = element_text(color = "red"),
        axis.text.y.right = element_text(colour = "red")) #ADD THIS
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 2011-06-13
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多