Reputation: 8480
I am trying to add a legend to a ggplot graph that uses solid and dashed lines.
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. 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?
Upvotes: 1
Views: 235
Reputation: 39613
Try this reshaping data to long, and then using a variable in the linetype statement. 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:
Upvotes: 2
Reputation: 174278
The alternative to reshaping if you only have two lines is to put the linetype as a character assignment inside 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))
Upvotes: 3