Search code examples
rggplot2chartsaxislinegraph

Secondary y axis R ggplot2


I need a graph with a secondary y axis like this, but I'm having some issues: Graph I want

I have tried a lot of changes in my code, but it seems like the axis scales are not working, and now this is what I got:

Graph I have now

This is the code that I'm using:

    # Datos Clorofila-Radiación
    horario <- c("D1-6:30", "D1-12:00", "D1-18:00", "D2-6:30", "D2-12:00", "D2-18:00", "D3-        6:30", "D3-12:00", "D3-18:00")
    trh3 <- c(1.85, 1.21, 2.23, 1.50, 1.11, 1.86, 1.74, 1.2, 1.63)
    trh5 <- c(1.99, 1.50, 1.98, 1.90, 1.14, 2.01, 1.59, 1.04, 1.53)
    rad <- c(22.53, 1909.10, 30.32, 22.32, 2342.10, 12.65, 28.70, 1279.8, 28.68)

    # Crear un data frame
    datos <- data.frame(horario, trh3, trh5, rad)

    # Ordenar los datos por el orden deseado en el eje x
   datos$horario <- factor(datos$horario, levels = c("D1-6:30","D1-12:00","D1-18:00","D2-6:30","D2-12:00","D2-18:00","D3-6:30","D3-12:00","D3-18:00"))

   # Gráfico
   ggplot(datos, aes(x = horario)) +
      geom_line(aes(y = trh3, color = "trh3", group = 1)) +
      geom_line(aes(y = trh5, color = "trh5", group = 1)) +
      geom_line(aes(y = rad, color = "rad", group = 1), linetype = "dashed") +
      scale_y_continuous(
        name = "Clorofila (µg/ml)",
        breaks = seq(1, 2.5, by = 0.2),
        labels = seq(1, 2.5, by = 0.2)) +
      scale_y_continuous(
        sec.axis = sec_axis(~./1000, name = "Radiación solar (W/m²)", breaks = seq(0, 2500, by = 500)/1000),
        name = "Radiación solar (W/m²)",
        breaks = seq(0, 2500, by = 500),
        labels = seq(0, 2500, by = 500)) +
      scale_color_manual(
        values = c("trh3" = "blue", "trh5" = "green", "rad" = "red"),
        labels = c("trh3 (Clorofila)" = "trh3", "trh5 (Clorofila)" = "trh5", "Radiación solar")) +
      labs(x = "Semana de medición", y = "Parámetros", color = "Variable") +
      theme_minimal() +
      theme(legend.position = "bottom")

Solution

  • You may have several issues with your code. This may fix some of them:

    ggplot(datos, aes(x = horario)) +
      geom_line(aes(y = trh3*1000, color = "trh3", group = 1)) +
      geom_line(aes(y = trh5*1000, color = "trh5", group = 1)) +
      geom_line(aes(y = rad, color = "rad", group = 1), linetype = "dashed") +
      scale_y_continuous(
        sec.axis = sec_axis(~./1000, name = "Radiación solar (W/m²)", breaks = seq(0, 2500, by = 500)/1000),
       name = "Clorofila (µg/ml)",
        breaks = seq(0, 2500, by = 500),
        labels = seq(0, 2500, by = 500)) +
      scale_color_manual(
        values = c("trh3" = "blue", "trh5" = "green", "rad" = "red"),
        labels = c("trh3 (Clorofila)" = "trh3", "trh5 (Clorofila)" = "trh5", "Radiación solar")) +
      labs(x = "Semana de medición", y = "Parámetros", color = "Variable") +
      theme_minimal() +
      theme(legend.position = "bottom")
    

    enter image description here