Search code examples
rggplot2

plotting 3 axes in R


I have a data frame like this:

df <- (category=c('a',   'b', 'c',  'd','e'),
         value1=c(1.02,-0.34,2.31, 1.15,0.68), 
         value2=c(-1.14,2.19,0.56, 3.12,1.17), 
         value3=c(    0,0.19,3.18,-1.14,2.12))

I want to ask if there is any possible way to plot a graph with value 1 is in the x-axis, and value 2 and 3 are in the y-axis (one on the left and the other on the right). I hope to be able to receive some help with this. Many thanks!


Solution

  • You mean like this?

    out

    library(ggplot2)
        
    df <- data.frame(
      category = c('a', 'b', 'c', 'd', 'e'),
      value1 = c(1.02, -0.34, 2.31,  1.15, 0.68),
      value2 = c(-1.14, 2.19, 0.56,  3.12, 1.17),
      value3 = c(0,     0.19, 3.18, -1.14, 2.12)
    )
    
    scale_factor <- diff(range(df$value2)) / diff(range(df$value3))
    
    ggplot(df, aes(x = value1)) +
      geom_line(aes(y = value2, color = "Value 2")) +
      geom_line(aes(y = value3 * scale_factor, color = "Value 3")) +
      scale_y_continuous(
        name = "Value 2",
        sec.axis = sec_axis(~./scale_factor, name = "Value 3")
      ) +
      scale_color_manual(values = c("Value 2" = "blue", "Value 3" = "red")) +
      labs(x = "Value 1", color = "Variables") +
      theme_minimal()
    

    with Labels instead of lines

    out

    # Create the plot with labels instead of lines
    ggplot(df, aes(x = value1)) +
      geom_text(aes(y = value2, label = category, color = "Value 2"), size = 4) +
      geom_text(aes(y = value3 * scale_factor, label = category, color = "Value 3"), size = 4) +
      scale_y_continuous(
        name = "Value 2",
        sec.axis = sec_axis(~./scale_factor, name = "Value 3")
      ) +
      scale_color_manual(values = c("Value 2" = "blue", "Value 3" = "red")) +
      labs(x = "Value 1", color = "Variables") +
      theme_minimal()