我有一个df看起来像这样的数据框
> dput(head(df))
structure(list(Percent = c(1, 2, 3, 4, 5), Test = c(4, 2, 3,
5, 2), Train = c(10, 12, 10, 13, 15)), .Names = c("Percent",
"Test", "Train"), row.names = c(NA, 5L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)
看起来像这样
Percent Test Train
1 4 10
2 2 12
3 3 10
4 5 13
5 2 15
Run Code Online (Sandbox Code Playgroud)
如何将Test和绘制Train成两条线ggplot?
我现在有这样的事情
ggplot(dfk, aes(x = Percent, y = Test)) + geom_point() +
geom_line()
Run Code Online (Sandbox Code Playgroud)
我还想添加Train连接到绘图上的点和线,并在图例中使用不同的颜色和标签。我不知道该怎么做。
有两种方法,添加图层或预先重组数据。
添加图层:
ggplot(df, aes(x = Percent)) +
geom_point(aes(y = Test), colour = "red") +
geom_line(aes(y = Test), colour = "red") +
geom_point(aes(y = Train), colour = "blue") +
geom_line(aes(y = Train), colour = "blue")
Run Code Online (Sandbox Code Playgroud)
重组您的数据:
# df2 <- tidyr::gather(df, key = type, value = value, -Percent) # Old way
df2 <- tidyr::pivot_longer(df, -Percent, names_to = "type", values_to = "value") # New way
ggplot(df2, aes(x = Percent, y = value, colour = type)) +
geom_point() +
geom_line()
Run Code Online (Sandbox Code Playgroud)
选项 2 通常是首选,因为它发挥了ggplot2的优势和优雅。