英文:
ggplot legend does not appear
问题
我的绘图代码如下:
ggplot(NULL, aes(V2, V1)) +
geom_line(data = df1, colour = "blue") +
geom_line(data = df2, colour = "green") +
geom_line(data = df3, colour = "purple") +
theme(
legend.position = "bottom") +
df1、df2 和 df3 具有以下相同的结构:
V2 V1
1 1.4
2 1.5
3 1.9
4 4.5
5 6.7
6 7.8
7 8.1
8 8.2
9 8.3
10 8.9
输出中未显示图例,但我需要在图上区分这些线。
英文:
My code for the plot is the following
ggplot(NULL, aes(V2, V1)) +
geom_line(data = df1, colour = "blue") +
geom_line(data = df2, colour = "green") +
geom_line(data = df3, colour = "purple") +
theme(
legend.position = "bottom") +
df1, df2, and df3 have the same following structure
V2 V1
1 1.4
2 1.5
3 1.9
4 4.5
5 6.7
6 7.8
7 8.1
8 8.2
9 8.3
10 8.9
The output does not show the legend, but I need to differentiate between the lines on the plot.
答案1
得分: 3
以下是翻译好的部分:
也许将数据放入一个数据框中会更有帮助,然后使用一个 geom_line
来绘制数据,而不是多个。
library(ggplot2)
dplyr::bind_rows(df1 = df1, df2 = df2, df3 = df3, .id = "id") %>%
ggplot() + aes(V2, V1, color = id) +
geom_line() +
theme(legend.position = "bottom")
数据:
df1 <- structure(list(V2 = 1:10, V1 = c(1.4, 1.5, 1.9, 4.5, 6.7, 7.8,
8.1, 8.2, 8.3, 8.9)), class = "data.frame", row.names = c(NA, -10L))
df2 <- structure(list(V2 = 1:10, V1 = c(1.43390152077191, 2.30610947613604,
2.23775280718692, 5.41628585802391, 7.05710641788319, 8.77536501311697,
8.48437852263451, 8.68867353517562, 8.7907762312796, 8.91225462416187
)), row.names = c(NA, -10L), class = "data.frame")
df3 <- structure(list(V2 = 1:10, V1 = c(2.04147320063785, 2.01257497165352,
2.22035211822949, 5.08143315766938, 7.31734440829605, 8.23827453767881,
8.27036898061633, 8.91508049662225, 9.04778654868715, 9.74391470812261
)), row.names = c(NA, -10L), class = "data.frame")
英文:
Maybe it would be helpful if you get the data into one dataframe, then plot the data with one geom_line
instead of multiple.
library(ggplot2)
dplyr::bind_rows(df1 = df1, df2 = df2, df3 = df3, .id = "id") %>%
ggplot() + aes(V2, V1, color = id) +
geom_line() +
theme(legend.position = "bottom")
data
df1 <- structure(list(V2 = 1:10, V1 = c(1.4, 1.5, 1.9, 4.5, 6.7, 7.8,
8.1, 8.2, 8.3, 8.9)), class = "data.frame", row.names = c(NA, -10L))
df2 <- structure(list(V2 = 1:10, V1 = c(1.43390152077191, 2.30610947613604,
2.23775280718692, 5.41628585802391, 7.05710641788319, 8.77536501311697,
8.48437852263451, 8.68867353517562, 8.7907762312796, 8.91225462416187
)), row.names = c(NA, -10L), class = "data.frame")
df3 <- structure(list(V2 = 1:10, V1 = c(2.04147320063785, 2.01257497165352,
2.22035211822949, 5.08143315766938, 7.31734440829605, 8.23827453767881,
8.27036898061633, 8.91508049662225, 9.04778654868715, 9.74391470812261
)), row.names = c(NA, -10L), class = "data.frame")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论