R:使用 ggplot 更改辅助轴刻度标签的颜色

use*_*648 3 visualization r data-visualization ggplot2 axis-labels

我正在尝试生成辅助轴刻度标签,其颜色与 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")
)
Run Code Online (Sandbox Code Playgroud)

示例图

小智 6

你的代码很好,只需在 theme() 中添加:

axis.text.y.right = element_text(colour = "red")
Run Code Online (Sandbox Code Playgroud)

像这样:

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
Run Code Online (Sandbox Code Playgroud)

祝你好运!

颜色刻度