You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为双Y轴双曲线添加图例并匹配Y轴标签颜色

ggplot2双Y轴曲线:设置Y轴标签与对应曲线同色

需求:用ggplot2绘制两条对应左右双Y轴的曲线,要求Y轴标签颜色和对应曲线颜色匹配。

现有实现代码:

library(readr)
library(ggplot2)
library(tibble)
library(hrbrthemes)
df <- read_csv("TS-ARTICLES.csv")
df <- as.data.frame(df)
p1 <- ggplot(df, aes(x = YEAR)) +
  geom_line(aes(y = HEURISTICS), color = "green") +
  geom_line(aes(y = HYPERHEURISTICS * 1267/45), color = "blue") +
  labs(title = "Time Series of Published Articles", 
       subtitle = "Scopus Search of Heuristics and Hyper-heuristics, accesed at 16 of october 2022", 
       x ="Year", 
       y ="Number of Heuristics Articles") +
  scale_x_continuous(breaks = seq(from = 1950, to = 2022, by = 10)) +
  scale_y_continuous(limits = c(0, 1267), 
                     sec.axis = sec_axis(~ . *45/1267, name = "Number of Hyper-heuristics Articles")) +
  theme(axis.text.x = element_text(angle=80, hjust=1), 
        title = element_text(face = "bold"), 
        panel.background = element_rect(fill = 'White', colour = 'black'), 
        panel.grid.major = element_line(colour = "gray"))
print(p1)

当前效果:
当前双Y轴图表效果

修改方案

只需在theme中添加左右Y轴标题的颜色设置,分别对应两条曲线的颜色即可:

修改后的完整代码:

library(readr)
library(ggplot2)
library(tibble)
library(hrbrthemes)
df <- read_csv("TS-ARTICLES.csv")
df <- as.data.frame(df)
p1 <- ggplot(df, aes(x = YEAR)) +
  geom_line(aes(y = HEURISTICS), color = "green") +
  geom_line(aes(y = HYPERHEURISTICS * 1267/45), color = "blue") +
  labs(title = "Time Series of Published Articles", 
       subtitle = "Scopus Search of Heuristics and Hyper-heuristics, accesed at 16 of october 2022", 
       x ="Year", 
       y ="Number of Heuristics Articles") +
  scale_x_continuous(breaks = seq(from = 1950, to = 2022, by = 10)) +
  scale_y_continuous(limits = c(0, 1267), 
                     sec.axis = sec_axis(~ . *45/1267, name = "Number of Hyper-heuristics Articles")) +
  theme(axis.text.x = element_text(angle=80, hjust=1), 
        title = element_text(face = "bold"), 
        panel.background = element_rect(fill = 'White', colour = 'black'), 
        panel.grid.major = element_line(colour = "gray"),
        # 添加Y轴标题颜色设置
        axis.title.y = element_text(color = "green"),
        axis.title.y.right = element_text(color = "blue"))
print(p1)

说明

  • axis.title.y对应左侧Y轴,设置为绿色(和HEURISTICS曲线同色)
  • axis.title.y.right对应右侧Y轴,设置为蓝色(和HYPERHEURISTICS曲线同色)

内容的提问来源于stack exchange,提问作者Eduardo Zárate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 05:45:34