Line plot legend does not appear

≡放荡痞女 提交于 2019-12-14 04:02:14

问题


I am trying to plot a line plot in r by using ggplot. Unfortunately, the legend does not show up. Can anyone help me?

My code looks like the following:

dfdatavgsM=data.frame(datum, avgsätzegespMT, avgsätzegespML)
 ggplot(data = dfdatavgsM, aes(x=datum, color=Wettbewerbsart))
+ geom_line(data=dfdatavgsM, aes(y = avgsätzegespML),color="red")
+ geom_line(data=dfdatavgsM, aes(y = avgsätzegespMT), color="blue")
+ geom_vline(xintercept=2011, size = 0.6)
+ scale_y_continuous(name="Anzahl an Sätzen")
+ scale_x_datetime(name = "Saison" ,date_breaks = ("2 year"),date_labels = "%Y") 
+ ggtitle("Wettbewerbsintensität in Spielen mit |∆TTR| ≤ 118") + theme(panel.background = element_rect(fill = "white", colour = "black")) 
+ theme(panel.grid.major = element_line(size = 0.25, linetype = 'solid', colour = "light grey")) + theme(axis.ticks = element_line(size = 1))

回答1:


The legend will only appear if you use color inside an aes statement. You will need to reshape your data to 'long' format (e.g. with tidyr::gather), and have a single geom_line term and an aes including color=type. Something like this (not tested as I don't have your data)...

library(tidyverse)

dfdatavgsM=data.frame(datum, avgsätzegespMT, avgsätzegespML)

dfdatavgsMlong <- dfdatavgsM %>% gather(key = type, value = value, -datum)

ggplot(data = dfdatavgsMlong, aes(x=datum, y=value, color=type)) + 
   geom_line()


来源:https://stackoverflow.com/questions/58817011/line-plot-legend-does-not-appear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!