0

so I have a two Y-Axis plot. Each Y-Axis is given a group of Data.

I want to have two different legends for each group on left and right side of plot on the locations shown in the second picture.

This is the code I am using:

coeff <- .025

Plot <- ggplot(df_visual_count_average, aes(x=cym)) +
  
  geom_line(aes(y = count_cont_res, color = "Count Cat1"), group = 1, size = 1.5) +
  geom_line(aes(y = count_fos_car, color = "Count Cat2"), group = 2, size = 1.5 ) +
  geom_line(aes(y = count_oth, color = "Count Cat3"), group = 3, size = 1.5) +
  geom_line(aes(y = count_SHSS_cont_res, color = "Count Cat4"), group = 4, size = 1.5) +
  
  geom_line(aes(y = ave_age_cont_res/coeff, color = "Ave age of Cat5"), group = 1, size = 1.5) +
  geom_line(aes(y = ave_age_fos_car/coeff, color = "Ave age of Cat6"), group = 2, size = 1.5 ) +
  geom_line(aes(y = ave_age_oth/coeff, color = "Ave age Cat7"), group = 3, size = 1.5) +
  geom_line(aes(y = ave_age_SHSS_cont_res/coeff, color = "Ave age Cat8"), group = 4, size = 1.5) +
  
  scale_y_continuous(  name = "Counts of Group1", sec.axis = sec_axis(~.*coeff, name="Average of Group 2") ) +
  
  ggtitle("Counts and Average of Group variation with time") 

Plot

The first pic is the current plot I am having and the later plot is the one I want to update to: current Plot:

I want this result

1
  • It would really help if you provided the data (df_visual_count_average).
    – Edward
    Commented May 14 at 3:40

1 Answer 1

1

The ggnewscale package allows you to add additional scales that are already in use.

library(ggplot2)
library(ggnewscale)

pivot_longer(df_visual_count_average, -cym,
             names_to=c(".value", "name"),
             names_pattern="(count|ave_age)_(.*)") |>
  ggplot(aes(x=cym)) +
  geom_line(aes(y = count, color = name), size = 1.5) +
  labs(color="Average of Group 2") +

  new_scale_color() +
  geom_line(aes(y = ave_age/coeff, color=name), size = 1.5) +
  scale_y_continuous(name = "Counts of Group 1", 
                     sec.axis = sec_axis(~.*coeff, name="Average of Group 2") ) +
  scale_color_manual(values=c("blue","green4","brown","orange")) +
  ggtitle("Counts and Average of Group variation with time") +
  guides(col=guide_legend(title="Count of Group 1", position="left"))

enter image description here


df_visual_count_average <- data.frame(
  cym=seq(2000,2024),
  count_cont_res=rnorm(25, 600, 100),
  count_fos_car=rnorm(25, 500, 100),
  count_oth=rnorm(25, 400, 50),
  count_SHSS_cont_res=rnorm(25, 300, 50),
  
  ave_age_cont_res=rnorm(25, 40, 5),
  ave_age_fos_car=rnorm(25, 30, 5),
  ave_age_oth=rnorm(25, 20, 5),
  ave_age_SHSS_cont_res=rnorm(25, 10, 5)
)

Not the answer you're looking for? Browse other questions tagged or ask your own question.