简体   繁体   English

将图例添加到由具有受控颜色的多个数据帧组成的ggplot中

[英]Adding legend to ggplot made from multiple data frames with controlled colors

I have a ggplot2 line chart made from three data frames for which I have controlled the color scheme. 我有一个由三个数据帧组成的ggplot2折线图,我已经为其控制了配色方案。 I've instead used linetype to distinguish between lines. 我改用linetype来区分线。 This leads to a situation in which a legend is not automatically generated. 这导致无法自动生成图例的情况。 How can I create a legend for this plot? 如何为该图创建图例?

tpAct <- data.frame(
  Date=seq.Date(as.Date('2017-09-01'), as.Date('2018-01-01'),by='month'),
  Reg1=rnorm(5, 10, 5),
  Reg2=rnorm(5, 15, 5),
  Reg3=rnorm(5, 20, 5),
  Reg4=rnorm(5, 25, 5),
  Reg5=rnorm(5, 30, 5),
  Total=rnorm(5, 60, 5)
)

tpOL <- data.frame(  
  Date=seq.Date(as.Date('2017-09-01'), as.Date('2018-01-01'),by='month'),
  Reg1=rnorm(5, 10, 5),
  Reg2=rnorm(5, 25, 5),
  Reg3=rnorm(5, 20, 5),
  Reg4=rnorm(5, 25, 5),
  Reg5=rnorm(5, 30, 5),
  Total=rnorm(5, 60, 5)
)

tpModL2 <- data.frame(  
  Date=seq.Date(as.Date('2017-09-01'), as.Date('2018-01-01'),by='month'),
  Reg1=rnorm(5, 10, 5),
  Reg2=rnorm(5, 25, 5),
  Reg3=rnorm(5, 20, 5),
  Reg4=rnorm(5, 25, 5),
  Reg5=rnorm(5, 30, 5),
  Total=rnorm(5, 60, 5)
)

ggplot() + 
  geom_line(data=tpAct, aes(x=Date, y=Reg1), color='red', size=1.25) +
  geom_line(data=tpAct, aes(x=Date, y=Reg2), color='blue', size=1.25) + 
  geom_line(data=tpAct, aes(x=Date, y=Reg3), color='green', size=1.25) + 
  geom_line(data=tpAct, aes(x=Date, y=Reg4), color='pink', size=1.25) + 
  geom_line(data=tpAct, aes(x=Date, y=Reg5), color='yellow', size=1.25) + 
  geom_line(data=tpAct, aes(x=Date, y=Total), color='black', size=1.25) + 
  geom_line(data=tpOL, aes(x=Date, y=Reg1), linetype=5, color='red', size=1.25) +
  geom_line(data=tpOL, aes(x=Date, y=Reg2), linetype=5, color='blue', size=1.25) +
  geom_line(data=tpOL, aes(x=Date, y=Reg3), linetype=5, color='green', size=1.25) +
  geom_line(data=tpOL, aes(x=Date, y=Reg4), linetype=5, color='pink', size=1.25) +
  geom_line(data=tpOL, aes(x=Date, y=Reg5), linetype=5, color='yellow', size=1.25) +
  geom_line(data=tpOL, aes(x=Date, y=Total), linetype=5, color='black', size=1.25) + 
  geom_line(data=tpModL2, aes(x=Date, y=Reg1), linetype=4, color='red', size=1.25) +
  geom_line(data=tpModL2, aes(x=Date, y=Reg2), linetype=4, color='blue', size=1.25) +
  geom_line(data=tpModL2, aes(x=Date, y=Reg3), linetype=4, color='green', size=1.25) +
  geom_line(data=tpModL2, aes(x=Date, y=Reg4), linetype=4, color='pink', size=1.25) +
  geom_line(data=tpModL2, aes(x=Date, y=Reg5), linetype=4, color='yellow', size=1.25) +
  geom_line(data=tpModL2, aes(x=Date, y=Total), linetype=4, color='black', size=1.25) +
  labs(x='', y='Total Balances ($B)')

在此处输入图片说明

Here's how to stack and plot the data using the sample data frames you provided: 以下是使用您提供的示例数据框堆叠和绘制数据的方法:

library(tidyverse)

setNames(list(tpAct, tpOL, tpModL2), c("tpAct","tpOL","tpModL2")) %>% 
  map_df(~ .x %>% gather(key, value, -Date), .id="source") %>% 
  ggplot(aes(Date, value, colour=key, linetype=source)) +
    geom_line() +
    scale_colour_manual(values=c('red','blue','green','pink', 'yellow', 'black')) +
    theme_classic()

setNames(list(tpAct, tpOL, tpModL2), c("tpAct","tpOL","tpModL2")) puts the three data frames in a list and assigns the data frame names as the names of the list elements. setNames(list(tpAct, tpOL, tpModL2), c("tpAct","tpOL","tpModL2"))将三个数据帧放入列表中,并将数据帧名称分配为列表元素的名称。

map_df(~ .x %>% gather(key, value, -Date), .id="source") converts the individual data frames to long format and stacks them into a single long-format data frame. map_df(~ .x %>% gather(key, value, -Date), .id="source")将单个数据帧转换为长格式,并将其堆叠为单个长格式数据帧。

Here's what the plot looks like: 这是情节的样子:

在此处输入图片说明

A faceted plot might be easier to read: 多面图可能更易于阅读:

setNames(list(tpAct, tpOL, tpModL2), c("tpAct","tpOL","tpModL2")) %>% 
  map_df(~ .x %>% gather(key, value, -Date), .id="source") %>% 
  ggplot(aes(Date, value, colour=key)) +
    geom_line() +
    scale_colour_manual(values=c('red','blue','green','pink', 'yellow', 'black')) +
    theme_classic() +
    facet_grid(~ source)

在此处输入图片说明

When you find yourself wanting to manually add a legend with ggplot2 , I've found it usually means you're going about making your plot in a way other than what ggplot2 intended. 当您发现想要使用ggplot2手动添加图例时,我发现它通常意味着您打算以不同于ggplot2的方式制作图。

To get ggplot to generate a legend for this plot, you need to reshape your data into a long format with groups before giving it to ggplot . 为了使ggplot为该图生成图例,您需要在将数据提供给ggplot之前将其数据ggplot为具有组的长格式。

You'll want to combine all three data sets (tpAct(), tpOL(), tpModL2() - I'm assuming that these are functions that are returning data frames) into a single data.frame -- let's call this combineddata. 您需要将所有三个数据集(tpAct(),tpOL(),tpModL2()-我假设这些是返回数据帧的函数)合并到单个data.frame中-我们称此合并数据。 The columns would then be: dataset (to denote which set the observation is from), Date, RegType (Reg1, Reg2,..Total), and Value (the actual y values you're plotting). 列将是:数据集(以表示观察值来自哪个集合),日期,RegType(Reg1,Reg2,.. Total)和值(您要绘制的实际y值)。

Then you could create a plot with something like the following: 然后,您可以使用以下内容创建图:

ggplot(combineddata, aes(x=Date, y=Value, color=RegType, linetype=dataset) + 
    geom_line()

This will draw one line for each combination of regression and data set like you have above, but will do so automatically and create a legend. 像上面一样,这将为回归和数据集的每种组合绘制一条直线,但是会自动绘制并创建图例。 If you don't like the colors and line types that ggplot picks for you, you can further specify the specific colors and line types you want to use with scales: 如果您不喜欢ggplot为您选择的颜色和线型, ggplot可以进一步指定要用于刻度的特定颜色和线型:

ggplot(combineddata, aes(x=Date, y=Value, color=RegType, linetype=dataset) + 
    geom_line() +
    scale_color_manual(values = c("red", "blue", "green", "pink", "yellow", "black")) + 
    scale_linetype_manual(values = c(1, 5, 4)

You may need to explicitly make RegType and dataset ordered factors before sending the data to ggplot to get them in the correct order, or change the order of the colors and line types above. 在将数据发送到ggplot之前,您可能需要显式地设置RegTypedataset有序因子,以正确的顺序获取它们,或者更改上面颜色和线型的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM