Search code examples
rggplot2plotyaxis

Change scale to secondary axis on a double line ggplot


I'm trying to plot a line chart in ggplot with two Y-axis. However, I can't make now of the lines corresponding to the secondary axis - it will only plot according to the primary one. Here is the code for the dataframe:

df <- data.frame(
  type = c("A", "B", "C", "D"),
  prop1 = c(0.31, 0.12, 0.55, 0.02),
  prop2 = c(0.16, 0.22, 0.15, 0.22)
)

df$type <- factor(df$type,
                  levels = c("D", "B", "A", "C")) #to reorder the plot

Now, the left Y-axis should correspond to prop1, while the right Y-axis should correspond to prop2. My code is as follows:

ggplot(df) +
  aes(x = type) +
  geom_point(aes(y = prop1), size = 2) +
  geom_line(aes(y = prop1), size = 1, group = 1) +
  geom_point(aes(y = prop2), size = 2, shape = 15) +
  geom_line(aes(y = prop2), size = 1, group = 1) +
  theme_bw() +
  labs(x = "") +
  scale_y_continuous(name = "prop1\n", 
                     breaks = seq(0,0.6,0.1),
                     limits = c(0,0.6),
                     labels = function(x) paste0(x * 100, "%"),
                     
                     sec.axis = sec_axis(~., name = "prop2"))

This code plots this:

enter image description here

The blue line (prop2) should be expanded to correspond to the right Y-axis (with the limits being, for example, [0.1, 0.25]). The problem is that that line is still being plotted according to the left Y-axis.

The desired plot would have the blue line with a bigger drop since the limits in the secondary axis (right) is smaller than the primary (left) one.

How can I fix this? Thanks!


Solution

  • One way could be using a coefficients:

    coeff <- 0.5
    
    ggplot(df, aes(x = type)) +
      geom_point(aes(y = prop1), size = 2, color = "red")+
      geom_line(aes(y = prop1), size = 1, group = 1, color = "red") +
      geom_point(aes(y = prop2 / coeff), shape=23, fill="blue", size=2) +
      geom_line(aes(y = prop2 / coeff), size = 1, group = 1, color = "blue") +
      scale_y_continuous(
        name = "Prop1",
        sec.axis = sec_axis(~.*coeff, name = "Prop2")
      ) +
      xlab("\n My x label")+
      theme_bw(14)+
      theme(
        axis.title.y = element_text(color = "red", size=13, face="bold"),
        axis.title.y.right = element_text(color = "blue", size=13, face="bold"),
        axis.text.x = element_text(angle = 45, vjust = 0.5, hjust=1)
      ) +
      ggtitle("My title")
    

    enter image description here