ggplot:两组的geom_line和geom_point重叠顺序?

时间:2020-03-31 18:10:44

标签: r ggplot2

我正在制作一个有光泽的应用程序,我先使用geom_line(aes(x= x, y =y, group = g, colour = g), size=2, na.rm=T),然后使用geom_point(aes(x= x, y = x, group = g, colour = g), size=5, na.rm=T, shape=16),然后在点的后面但在点的上方有一组线(此处为绿色)。另一组(粉红色)。

enter image description here


代码:

library(ggplot2)
ggplot(data=df2, aes(x=DateRelCases, y = CasesCumMod)) +
  geom_line(aes(x= DateRelCases, y =CasesCumMod, group = Country, colour = Country), size=2, na.rm=T) +
  geom_point(aes(x= DateRelCases, y =CasesCumMod, group = Country, colour = Country),size=5, na.rm=T, shape=16)

数据:

df2 <- data.frame(Country = structure(c(rep(2L, 30), rep(3L, 30), rep(1L, 30)), .Label = c("ES", "FR", "IT"), class = "factor"), 
                      DateRelCases = structure(rep(30:1,3)), 
                      CasesCumMod = c(40174, 37575, 32964, 29155, 25233, 22302, 
                                      19856, 16018, 14459, 12612, 10995, 9134, 7730, 6633, 5423, 
                                      4499, 3661, 2876, 2281, 1784, 1412, 1126, 716, 613, 423, 
                                      285, 212, 178, 130, 100, 97689, 92472, 86498, 80539, 74386, 
                                      69176, 63927, 59138, 53578, 47021, 41035, 35713, 31506, 27980, 
                                      23980, 17750, 17660, 15113, 12462, 10149, 9172, 7375, 5883, 
                                      4636, 3858, 3089, 2502, 1835, 1689, 1128, 78797, 72248, 64059, 
                                      56188, 47610, 39673, 33089, 28572, 24926, 19980, 17147, 13716, 
                                      11178, 9191, 7753, 5753, 4231, 3004, 2140, 1639, 1204, 589, 
                                      430, 374, 261, 200, 151, 114, 83, 66))

1 个答案:

答案 0 :(得分:1)

分层首先受到函数调用顺序的影响(geom_line之前,因此受geom_point的影响),其次受到数据中factor(级别)的影响(使用{ {1}}和其他分组美学)。这就是为什么所有点都位于线条顶部的原因。

要添加红线,红点,蓝线,蓝点(或任何颜色顺序),您需要按预期/需要的顺序显式地进行添加。显然,这破坏了它的一些可编程性,但是您得到了想要的分层。 (如果需要,您可以通过某种度量标准来影响group=的顺序,因此它仍然是可编程的……只是在cntry的说法中不容易。)

ggplot2

(对于这个较小的图像,我将gg <- ggplot(data=df2, aes(x=DateRelCases, y = CasesCumMod)) + ggdark::dark_theme_dark() for (cntry in unique(df2$Country)) { gg <- gg + geom_line(aes(x = DateRelCases, y =CasesCumMod, group = Country, colour = Country), size = 1, na.rm = TRUE, data = df2[df2$Country == cntry,]) + geom_point(aes(x = DateRelCases, y =CasesCumMod, group = Country, colour = Country), size = 3, shape = 16, na.rm = TRUE, data = df2[df2$Country == cntry,]) } 缩小了一点,与您的原始尺寸一样。)

ggplot2 with correct layers

相关问题