[英]Legend does not show up in ggplot2
I have the following code:我有以下代码:
ggplot(TC_merge, aes(x=Location)) +
geom_line(aes(y = C_r_base), color = "black", linetype="dashed") +
geom_line(aes(y = C_a_base), color = "navyblue") +
geom_line(aes(y = C_a_after), color = "red4") + theme_classic() +
theme(legend.position="right") +
labs(x = "Distance from CBD (kilometres)",
y = "Round-trip generalised transport costs (DKK)") +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
theme(text=element_text(family="Cambria", size=12))
And I get the following graph (without legend):我得到以下图表(没有图例):
Here is the data:这是数据:
Location C_r_base C_a_base C_a_after
0.01 59.09 80.0629 57.5824
0.02 54.18 80.1257 57.6648
0.03 54.27 80.1886 57.7473
0.04 54.36 80.2515 57.8297
I know the data has to be tidy for the legend to work, but rail still has to be a dotted line in the legend, so I'm not sure how to make that distinction manually.我知道数据必须整洁才能使图例起作用,但铁路仍然必须是图例中的虚线,所以我不确定如何手动进行区分。
All you needed to do is move the color
param inside the aes
您需要做的就是在
aes
中移动color
参数
library(ggplot2)
# Sample data using dput
TC_merge <- structure(list(Location = c(0.01, 0.02, 0.03, 0.04), C_r_base = c(59.09,
54.18, 54.27, 54.36), C_a_base = c(80.0629, 80.1257, 80.1886,
80.2515), C_a_after = c(57.5824, 57.6648, 57.7473, 57.8297)), row.names = c(NA,
-4L), class = "data.frame")
# create the manual color scale
manual_color_scale <- c("black", "navyblue", "red4")
names(manual_color_scale) <- c("black", "navyblue", "red4")
ggplot(TC_merge, aes(x=Location)) +
# Here I move the color param inside - Though it is a value.
# The actual color could be random generated.
# So it is needed to define the color scale
geom_line(aes(y = C_r_base, color = "black"), linetype="dashed",
# I use the size for bigger line to see the color better
size = 1) +
geom_line(aes(y = C_a_base, color = "navyblue"), size = 1) +
geom_line(aes(y = C_a_after, color = "red4"), size = 1) + theme_classic() +
theme(legend.position="right") +
labs(x = "Distance from CBD (kilometres)",
y = "Round-trip generalised transport costs (DKK)") +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
# Here I defined the manual scale for color
scale_color_manual(values = manual_color_scale) +
theme(text=element_text(family="Cambria", size=12))
Here is the plot with legend这是带有图例的 plot
Created on 2021-03-31 by the reprex package (v1.0.0)由代表 package (v1.0.0) 于 2021 年 3 月 31 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.