【问题标题】:How to control which factor is plotted first in ggplot2?如何控制在ggplot2中首先绘制哪个因子?
【发布时间】:2018-05-26 20:49:45
【问题描述】:
d1 <- data.frame(x = runif(n = 10000, min = 0, max = 1), y = 
rnorm(10000, sd = 0.2), type = "d1")
d2 <- data.frame(x = runif(n = 10000, min = 0, max = 1), y = 
rnorm(10000, mean = 0.2, sd = 0.2), type = "d2")
all_d <- rbind(d1, d2)
ggplot(all_d, aes(x = x, y = y, color = type)) + geom_point()

在这里您可以看到d2 点绘制在d1 点之上。因此,我尝试使用forcats::fct_relevel 进行更改

all_d_other <- all_d
all_d_other$type <- forcats::fct_relevel(all_d_other$type, "d2", "d1")
ggplot(all_d_other, aes(x = x, y = y, color = type)) + geom_point()

并且d2 点仍然在d1 点之上。有没有办法改变它,使d1 点位于d2 点之上?

【问题讨论】:

  • 你试过普通的基础?relevel吗?最坏的情况,您可以为 d1 添加单独的 +geom_point(),这将迫使它们被绘制在第二个(在顶部)
  • R 3.4.2,ggplot2 2.2.1.9000
  • @C8H10N4O2,我没有尝试基本的“relevel”,因为“levels”似乎按照我的预期进行了修改,并且颜色的变化也显示了
  • 参见stackoverflow.com/questions/15706281/…,显然绘制顺序受数据框当前顺序的影响,而不是因子水平。这可能算作对那个问题的欺骗。

标签: r ggplot2


【解决方案1】:

只需更改您的排序顺序,使您想要在顶部的点位于数据框的最后一行。

all_d <- all_d[order(all_d$type, decreasing=TRUE),]

ggplot(all_d, aes(x = x, y = y, color = type)) + 
  geom_point()

有关其他排序方式,请参阅dplyr::arrange 或非常快的data.table::setorder.

另一种解决方案,有点老套:

您可以重新绘制您的 d1,以便它们显示在顶部。

ggplot(all_d, aes(x = x, y = y, color = type)) + 
  geom_point()+
  geom_point(data=all_d[all_d$type=='d1',]) # re-draw d1's 

结果(无论哪种方式)

【讨论】:

  • 这行得通,但感觉很hackish。理想情况下,对因素进行重新排序,使其“起作用”。
  • @rmflight 现在怎么样?
猜你喜欢
  • 2012-01-10
  • 2014-11-23
  • 2012-04-10
  • 1970-01-01
  • 2018-12-10
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 2016-05-14
相关资源
最近更新 更多