使用多个变量时更改图例标签

Changing legend labels when using multiple variables

在 R 中使用 ggplot: 我正在尝试绘制一个包含多个列的线图作为单个变量。我没有使用 fill = 参数,所以我知道这就是 scale_fill_discrete 不起作用的原因。从我从其他类似问题中看到的情况来看,似乎所有其他选项(scale_colour_discrete、scale_shape_discrete 等)都要求您在构建绘图的第一步中使用这些参数。这可能是我的主要问题,但我不知道如何用三个不同的变量来解决它。现在显示的图例显示了三种不同的颜色,但它们与正确的变量没有关联。

ggplot(summary_5yr) + 
geom_line(aes(x = Year, y = NY_Med_Inc, group = 1, color ="blue")) +
geom_line(aes(x = Year, y = FL_Med_Inc, group = 1, color = "red")) +
geom_line(aes(x = Year, y = WA_Med_Inc, group = 1, color = "green")) +
labs(title = "Median Income Trends", x = "Year", y = "Median Income (USD)")

试试这个。要获得正确的颜色和图例,您必须使用 scale_color_manual。在 aes() 中使用 color = "blue" 不会将颜色设置为“蓝色”。相反,“蓝色”只是一种标签,您必须在 scale_color_manual 内为其分配颜色。还。要获得正确的标签,您必须设置 labels 参数。

实现所需情节的第二种方法是通过例如将您的 df 重塑为长格式tidyr::pivot_longer。这样只需要一个 geom_line 层,你会自动得到正确的标签。

library(ggplot2)
library(tidyr)
library(dplyr)

set.seed(123)

summary_5yr <- data.frame(
  Year = 2010:2020,
  NY_Med_Inc = runif(11, 10000, 50000),
  FL_Med_Inc = runif(11, 10000, 50000),
  WA_Med_Inc = runif(11, 10000, 50000)
)

ggplot(summary_5yr) + 
  geom_line(aes(x = Year, y = NY_Med_Inc, group = 1, color ="blue")) +
  geom_line(aes(x = Year, y = FL_Med_Inc, group = 1, color = "red")) +
  geom_line(aes(x = Year, y = WA_Med_Inc, group = 1, color = "green")) +
  scale_color_manual(values = c(blue = "blue", red = "red", green = "green"),
                     labels = c(blue = "NY_Med_Inc", red = "FL_Med_Inc", green = "WA_Med_Inc")) +
  labs(title = "Median Income Trends", x = "Year", y = "Median Income (USD)")

summary_5yr %>% 
    tidyr::pivot_longer(-Year, names_to = "var", values_to = "value") %>% 
    ggplot() + 
    geom_line(aes(x = Year, y = value, group = var, color = var)) +
    scale_color_manual(values = c(NY_Med_Inc = "blue", FL_Med_Inc = "red", WA_Med_Inc = "green")) +
    labs(title = "Median Income Trends", x = "Year", y = "Median Income (USD)")