辅助 y 轴 R ggplot2

问题描述 投票:0回答:1

我需要一个带有像这样的辅助 y 轴的图表,但我遇到了一些问题:Graph I want

我在代码中尝试了很多更改,但轴刻度似乎不起作用,现在这就是我得到的:

Graph I have now

这是我正在使用的代码:

    # 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")
r ggplot2 charts axis linegraph
1个回答
0
投票

您的代码可能存在多个问题。这可能会修复其中一些问题:

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

© www.soinside.com 2019 - 2024. All rights reserved.