简体   繁体   English

根据线型向ggplot折线图添加图例

[英]Add legend to ggplot line graph based on linetype

I am trying to add a legend to a ggplot graph that uses solid and dashed lines.我正在尝试将图例添加到使用实线和虚线的 ggplot 图中。

require(ggplot2)

DATE <- c("2020-10-14", "2020-10-15", "2020-10-16", "2020-10-17", "2020-10-18")
TMAX <- c(47, 45, 43, 40, 4)
TMIN <- c(35, 34, 28, 26, 29)

df <- data.frame(DATE, TMAX, TMIN)

ggplot(data = df, aes(x = DATE, y = TMIN, group = 1)) +
  geom_path(linetype = 1, size = 1.5) +
  labs(x = "Date",
       y = "Temp (F)") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
  geom_path(data = df, linetype = 2, size = 1.5, aes(x = DATE, y=TMAX)) 

在此处输入图像描述

A similar question states that I should include linetype within aes , although this does not yield a legend.一个类似的问题指出我应该在aes中包含linetype ,尽管这不会产生图例。 For example:例如:

ggplot(data = df, aes(x = DATE, y = TMIN, group = 1, linetype = 1)) +
  geom_path(size = 1.5) +
  labs(x = "Date",
       y = "Temp (F)") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + 
  geom_path(data = df, size = 1.5, aes(x = DATE, y=TMAX, linetype=2)) 

Here is the error:这是错误:

Error: A continuous variable can not be mapped to linetype

How can I add a legend to the figure showing both my solid line and dashed line?如何向显示我的实线和虚线的图形添加图例?

Try this reshaping data to long, and then using a variable in the linetype statement.尝试将此数据整形为 long,然后在 linetype 语句中使用变量。 In that way you can obtain the legend.这样就可以获得传说了。 Here the code:这里的代码:

require(ggplot2)
require(tidyr)
require(dplyr)
#Data
DATE <- c("2020-10-14", "2020-10-15", "2020-10-16", "2020-10-17", "2020-10-18")
TMAX <- c(47, 45, 43, 40, 4)
TMIN <- c(35, 34, 28, 26, 29)
df <- data.frame(DATE, TMAX, TMIN)
#Plot
df %>% pivot_longer(-DATE) %>%
  ggplot(aes(x = DATE, y = value, group = name,linetype=name)) +
  geom_path(size = 1.5) +
  labs(x = "Date",
       y = "Temp (F)") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+
  scale_linetype_manual(values=c(2,1))+labs(linetype='Var')+
  guides(linetype = guide_legend(override.aes = list(size = 0.5)))

Output: Output:

在此处输入图像描述

The alternative to reshaping if you only have two lines is to put the linetype as a character assignment inside aes如果您只有两行,则重塑的替代方法是将线型作为字符分配放在aes

ggplot(data = df, aes(x = DATE, y = TMIN, group = 1)) +
  geom_path(aes(linetype = "TMIN"), size = 1.5) +
  geom_path(aes(y = TMAX, linetype = "TMAX"), size = 1.5) +
  labs(x = "Date", y = "Temp (F)") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))

在此处输入图像描述

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

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