如何在 ggplot 中创建一个图例,将名称和颜色分配给列而不是数据框列中的值?

How can I create a legend in ggplot which assigns names and colors to columns and not to values within a column of a dataframe?

我一直在寻找在 ggplot 中创建图例的想法,但所有解决方案都只提供图例,这些图例将数据框中单个列的数据按颜色和名称划分为不同的组,组 =“columnname”。 这是给定的数据帧的头部:

ewmSlots ewmValues ewmValues2 ewmValues3
1 0.7785078 0.7785078 0
2 0.7198410 0.7491744 0
3 0.7333798 0.7412771 0
4 0.9102729 0.8257750 0
5 0.7243151 0.7750450 0
6 0.8706777 0.8228614 0

现在我想要一个图例,以其各自的名称和颜色显示 ewmValues、ewmValues2 和 ewmValues3。

举一个简单的例子,我找到的其他解决方案可以解决类似的问题

time sex
lunch male
dinner female
dinner male
lunch female

传说会显示性别和每种性别的颜色,这显然不是问题所在 我想在这里解决。

仅融化数据怎么样(我们将上面的示例称为名为 ewm 的数据框)?

# With melt
ggplot(melt(ewm, id.vars = "ewmSlots"), aes(ewmSlots, value, color=variable, stat='identity')) +
  geom_line(size=1.4) + labs(color="")

如果你反对融化,下面给出了完全相同的东西:

# Without melt
ggplot(ewm, aes(ewmSlots)) + 
  geom_line(aes(y=ewmValues, color="ewmValues"), size=1.4) + 
  geom_line(aes(y=ewmValues2, color="ewmValues2"), size=1.4) + 
  geom_line(aes(y=ewmValues3, color="ewmValues3"), size=1.4) + 
  labs(color="", y="value")