R:标签未显示在 ggplot2 图表中

R: Labels not displaying at a ggplot2 graph

鉴于此 R 脚本:

library(glue)
library(ggplot2)

ir.data <- read.csv(file="~/apps/mine/cajueiro_weather_station/sensor_data/temperature_data.csv", header = F)
ir.data$V1 <- as.POSIXct(ir.data$V1, format = "%Y-%m-%dT%H:%M:%S", tz = "UTC")
ir.data$size <- (ir.data$V2 - ir.data$V3)

ggplot(ir.data, aes(x=V1)) +
  labs(title = "IR-radiation-based sky temperature monitoring.",
       subtitle = glue("Samples from {ir.data$V1[1]}h to {tail(ir.data$V1, n=1)}h UTC-3."),
       caption = "Cajueiro Weather Station - fschuindt.githhub.io/blog/weather") +
  geom_line(aes(y = V2), color = "#6163c2") +
  geom_line(aes(y = V3), color = "#ad1fa2") +
  scale_color_discrete(name = "Labels", labels = c("Ambient temperature.", "Sky temperature.")) +
  xlab("Timestamp") +
  ylab("Measured temperature in °Celcius")

而这个 .csv 数据样本:

2022-04-30T19:47:00,28.03,28.05
2022-04-30T19:47:02,27.99,28.01
2022-04-30T19:47:04,28.07,28.01
2022-04-30T19:47:06,28.05,28.05
2022-04-30T19:47:08,28.05,28.01
2022-04-30T19:47:10,28.03,28.01
2022-04-30T19:47:12,28.05,27.99
2022-04-30T19:47:14,28.07,28.01
2022-04-30T19:47:16,28.07,28.05
2022-04-30T19:47:18,28.05,28.05
2022-04-30T19:47:20,28.09,28.07

这是绘图输出(.csv 数据比示例大):

为什么 scale_color_discrete(name = "Labels", labels = c("Ambient temperature.", "Sky temperature.")) 中描述的标签没有显示?

在对 colouraes 调用中无法识别这些值。重塑数据以将所有 y 值放在一个列中,将分组变量传递给 aes(colour = ...) 并使用 scale_colour_manual 设置颜色:

library(tidyverse)

ir.data <- read_csv(
  "2022-04-30T19:47:00,28.03,28.05
2022-04-30T19:47:02,27.99,28.01
2022-04-30T19:47:04,28.07,28.01
2022-04-30T19:47:06,28.05,28.05
2022-04-30T19:47:08,28.05,28.01
2022-04-30T19:47:10,28.03,28.01
2022-04-30T19:47:12,28.05,27.99
2022-04-30T19:47:14,28.07,28.01
2022-04-30T19:47:16,28.07,28.05
2022-04-30T19:47:18,28.05,28.05
2022-04-30T19:47:20,28.09,28.07",
col_names = c("V1", "V2", "V3")
)


ir.data %>%
  pivot_longer(-V1, names_to = "Labels", values_to = "V") %>%
  ggplot(aes(x = V1, y = V, colour = Labels)) +
  labs(
    title = "IR-radiation-based sky temperature monitoring.",
    subtitle = glue::glue(
      "Samples from {ir.data$V1[1]}h to {tail(ir.data$V1, n=1)}h UTC-3."
    ),
    caption = "Cajueiro Weather Station - fschuindt.githhub.io/blog/weather"
  ) +
  geom_line(size = 1) +
  scale_color_manual(
    name = "Labels",
    ,
    values = c("#6163c2", "#ad1fa2"),
    limits = c("V2", "V3"),
    labels = c("Ambient temperature.", "Sky temperature."),
  ) +
  xlab("Timestamp") +
  ylab("Measured temperature in °Celcius")

reprex package (v2.0.1)

创建于 2022-05-06