I've been trying for a while now and also doing a lot of research, but I just can't get it to add a simple legend for my two lines.
I have two lines in my chart and I just want to add a legend for the two lines.
scale_color_manual did not work. I suspect it is because I am using scale_y_break. In other plots (without scale_y_break) scale_color_manual works without problems.
Here is my code:
day <- c(1:5)
altimeter <- c(8.291, 8.872, 7.212, 8.1, 5.92)
slope_kilometers <- c(30.23, 34.8, 29.34, 32.98, 21.23)
df2 <- data.frame(day, altimeter, slope_kilometers)
library(ggbreak)
altimeter_color <- "steelblue"
slope_kilometers_color <- "darkred"
ggplot(df2, aes(x = day))
#Altimeter data
geom_line(aes(y = altimeter),
linetype = 2,
linewidth = 1,
color = altimeter_color)
geom_point(y = altimeter, size = 3, color = altimeter_color)
#Slope kilometers data
geom_line(aes(y = slope_kilometers),
linetype = 2,
linewidth = 1,
color = slope_kilometers_color)
geom_point(y = slope_kilometers, size = 3, color = slope_kilometers_color)
#Y-Axis
scale_y_break( c(9, 20), scales = 1.5)
#Label
labs(x = "Tage",
y = "[km]")
#Legend
scale_color_manual(values = c(altimeter_color, slope_kilometers_color))
#Title
ggtitle("Höhenmeter und Pistenkilometer meines 5-tägigen Skiurlaubs")
I tried different versions of scale_color_manual
, labs
, aes(fill="")
CodePudding user response:
Update: I tweaked the former plot (removed):
One way to achieve what you want is:
First bring data in long format then put color
inside aesthetics
:
Rule of thumb: What is in aesthetics will have a legend:
library(tidyverse)
library(ggbreak)
df2 %>%
pivot_longer(-day) %>%
ggplot(aes(x = day))
#Altimeter data
geom_line(data = . %>% filter(name == "altimeter"), aes(y = altimeter, color = name),
linetype = 2, linewidth = 1 )
geom_point(data = . %>% filter(name == "altimeter"), aes(y = altimeter, color = name), size = 3)
#Slope kilometers data
geom_line(data = . %>% filter(name == "slope_kilometers"), aes(y = slope_kilometers, color = name),
linetype = 2, linewidth = 1)
geom_point(data = . %>% filter(name == "slope_kilometers"), aes(y = slope_kilometers, color = name), size = 3)
#Y-Axis
scale_y_break( c(9, 20), scales = 1.5)
#Label
labs(x = "Tage", y = "[km]", color = "")
#Legend
scale_color_manual(values = c(altimeter_color, slope_kilometers_color))
#Title
ggtitle("Höhenmeter und Pistenkilometer meines 5-tägigen Skiurlaubs")
theme(legend.position = "bottom")