在同一图表上绘制两个geom_line和geom_point

4

我有一个数据框 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")

看起来是这样的

Percent    Test    Train
1          4       10
2          2       12
3          3       10
4          5       13
5          2       15

我该如何使用 ggplotTestTrain 绘制成两条线?

目前我的绘图结果如下:

ggplot(dfk, aes(x = Percent, y = Test)) + geom_point() + 
  geom_line() 

我还想在图表上添加Train点和连接线,并以不同的颜色和标签显示在图例中。我不确定如何做到这一点。

enter image description here

1个回答

7

有两种方式,要么添加层级结构,要么事先重构你的数据。

添加层级结构:

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")

重新组织您的数据:
# 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()

通常情况下,选择方案2更受欢迎,因为它发挥了ggplot2的优势和优雅之处。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接