首页 > 解决方案 > ggplot2 绘制线和点的顺序

问题描述

这里有很多关于如何在数据顶部绘制特定线或点的问题ggplot2。目前执行此操作的方法对于geom_point(取决于 data.frame 的实际顺序)和geom_line(取决于因子级别)是不同的。

我想知道是否有人知道它们为什么不同,以及是否有任何改变它们的计划。我希望如果我知道为什么那么它可以帮助使它更令人难忘,因为目前每次我想改变绘图顺序时,我最终都会感到沮丧。

我已经根据多年前的这个问题举了一个例子来说明这一点

更改ggplot中行的重叠顺序

请注意,我不是在问如何做到这一点(你可以在下面看到我知道怎么做),而是为了更好地理解为什么会这样(因此我认为这个问题不是重复的)看)

library(ggplot2)
  #data
pl_data <- structure(list(x = c(1, 1.5, 2, 1, 1.3, 1.4, 1.51, 2, 1, 1.31, 2),
                          y = c(0, 0.5, 1, 1, 0.7, 0.7, 0.5, 0, 0.7, 0.7, 0.7),
                          col = c("r", "r", "r", "b", "b", "b", "b", "b", "g", "g", "g")), 
                     row.names = c(NA, -11L), class = c("tbl_df", "tbl", "data.frame"))


#starting plot
plt1 <- ggplot(pl_data, aes(x = x, y = y, color = col)) +
  geom_line(size = 3)+
  scale_colour_manual(values = c("r"="Red","b"="blue","g"="green"))

#change factor to change lines
pl_data2 <- pl_data
pl_data2$col <- factor(pl_data2$col, c("g", "r", "b"))

plt2 <- plt1 %+% pl_data2

#But the points are still the same way around as in original
plt1 + geom_point(size = 5)

plt2 + geom_point(size = 5)

#reorder data to chnage the points
pl_data3 <- pl_data2[order(pl_data2$col),]

plt3 <- plt1 %+% pl_data3
plt3+ geom_point(size = 5)

reprex 包(v0.3.0)于 2019 年 11 月 12 日创建

标签: rggplot2

解决方案


推荐阅读