当出现2条不同的行时,我不知道如何向此散点图添加图例。我已经尝试了不同类型的解决方案(例如添加scale_colour_manual),但是它不起作用。
这是代码。它可以正确生成图形,但不会显示图例。
months <- c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
num_17 <- c(NA, 12, 20, 25, 13, 22, 6, 55, 7, 44, 14, 11)
num_18 <- c(33, 21, 45, 31, 27, 42, 16, 38, 22, 19, 39, 9)
time_df <- data.frame("Months" = months, "Submissions 2017" = num_17, "Submissions 2018" = num_18)
two_colors <- c("lightblue", "orange")
time_df$Months <- factor(time_df$Months, levels=c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"))
ggplot(time_df, aes(x = Months, color = Months, group = 1)) +
geom_line(y = num_17, size = 2, colour = "lightblue") +
geom_line(y = num_18, size = 2, colour = "orange") +
geom_point(aes(y = num_17), size = 3, color = "blue") +
geom_point(aes(y = num_18), size = 3, color = "red") +
xlab("2017 and 2018") + ylab("Number Submissions") +
ggtitle("Submissions By Month (2017 and 2018)") + theme_bw()+
scale_colour_manual(name="Legend", values = c(num_17 = "2017", num_18 = "2018"))+
theme(axis.text = element_text(size = 15),
axis.title.y = element_text(size = 20, margin = margin(r = 25)),
axis.title.x = element_text(size = 20, vjust = -7),
plot.title = element_text(size = 22, face = "bold"),
plot.margin = unit(c(1,1,1,1), "cm"))
我只想要一个标记每个组的图例。预先感谢。
答案 0 :(得分:1)
这应该做您想要的:
ggplot(time_df, aes(x = Months, group = 1)) +
geom_line(aes(y = Submissions.2017, color="2017"), size=2) +
geom_line(aes(y = Submissions.2018, color="2018"), size=2) +
geom_point(aes(y = Submissions.2017), size = 3, color="blue") +
geom_point(aes(y = Submissions.2018), size = 3, color="red") +
xlab("2017 and 2018") +
ylab("Number Submissions") +
ggtitle("Submissions By Month (2017 and 2018)") +
scale_colour_manual(values = c("lightblue", "orange")) +
theme_bw()+
theme(axis.text = element_text(size = 15),
axis.title.y = element_text(size = 20, margin = margin(r = 25)),
axis.title.x = element_text(size = 20, vjust = -7),
plot.title = element_text(size = 22, face = "bold"),
plot.margin = unit(c(1,1,1,1), "cm"))