Home > Net >  Inserting legend for two curves with 2 different y-axis-scale, and with its respective y-labels colo
Inserting legend for two curves with 2 different y-axis-scale, and with its respective y-labels colo

Time:10-18

I hope someone can give me some guidance for the following:

I want to plot two curves that have their own y-axis (left/right), and I want to change the color of the y-label, so that it matches the color of the curve. I have the following code:

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)

enter image description here

CodePudding user response:

The color for the axis labels could be set via theme options axis.title.y.left and axis.title.y.right. To add an additional legend move color=... inside aes(), then use scale_color_manual to set the right colors and labels:

Using some fake example data:

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")
  )

  • Related