首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为两条具有两个不同y轴比例的曲线插入图例,并具有各自的y标签颜色。

为两条具有两个不同y轴比例的曲线插入图例,并具有各自的y标签颜色。
EN

Stack Overflow用户
提问于 2022-10-17 05:03:40
回答 1查看 26关注 0票数 0

我希望有人能就以下几点给我一些指导:

我想要画出两条有自己的y轴(左/右)的曲线,我想要改变y-标签的颜色,使它与曲线的颜色相匹配。我有以下代码:

代码语言:javascript
复制
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)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-17 06:09:28

轴标签的颜色可以通过主题选项axis.title.y.leftaxis.title.y.right来设置。若要添加附加图例,请将color=...移动到aes()中,然后使用scale_color_manual设置正确的颜色和标签:

使用一些假的示例数据:

代码语言:javascript
复制
library(ggplot2)

df <- data.frame(
  YEAR = 1950:2022,
  HEURISTICS = seq(0, 1267, length.out = 73),
  HYPERHEURISTICS = seq(0, 40, length.out = 73)
)

ggplot(df, aes(x = YEAR)) +
  geom_line(aes(y = HEURISTICS, color = "green")) +
  geom_line(aes(y = HYPERHEURISTICS * 1267 / 45, color = "blue")) +
  scale_color_manual(values = c(green = "green", blue = "blue"), 
                     labels = c(green = "HEURISTICS", blue = "HYPERHEURISTICS")) +
  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")
  ) +
  theme(
    axis.title.y.left = element_text(color = "green"),
    axis.title.y.right = element_text(color = "blue")
  )

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74092768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档