在R中的geom_line顶部覆盖geom_point

Can*_*ice 3 r ggplot2

以下是在另一个软件中创建的图表的屏幕截图,该图表在折线图的顶部创建散点图,其中线条隐藏在散点图的位置.这就是我在R中要做的事情.

在此输入图像描述 当我在我的图表和数据上运行以下代码时:

dput(my_df)
structure(list(lastFinancingYear = c(2010, 2011, 2012, 2013, 
2014, 2015, 2016, 2017, 2018), raiseMedVal = c(5.33287671232877, 
5.03424657534247, 4.96986301369863, 7.36986301369863, 6.44383561643836, 
7.73835616438356, 8.4958904109589, 9.9054794520548, 9.43013698630137
), foundMedVal = c(11.0821917808219, 10.5178082191781, 8.62191780821918, 
10.2520547945205, 10.9643835616438, 10.9342465753425, 12.9945205479452, 
13.5397260273973, 12.6301369863014)), row.names = c(NA, -9L), class = c("tbl_df", 
"tbl", "data.frame"))

my_df %>% ggplot() +
  geom_line(aes(x = lastFinancingYear, y = raiseMedVal), size = 1.0, color = "#DDBB7B") +
  geom_point(aes(x = lastFinancingYear, y = raiseMedVal), shape = 1, size = 3.0, color = "#DDBB7B") +
  geom_line(aes(x = lastFinancingYear, y = foundMedVal), size = 1.0)
Run Code Online (Sandbox Code Playgroud)

...然后我得到一个如下图:

在此输入图像描述

存在散射标记并位于线的顶部,但线不会隐藏在标记后面,并且散点标记也没有粗体/厚度标记.我不知道如何解决这些,任何帮助表示赞赏!

提前致谢!

Mar*_*ius 5

您需要进行一些调整才能使其正常工作:

  • 使用填充的点形状之一,如形状 21。您可以检查这些点形状example("points")并转到第三个图。
  • 使用fill = "white"(或其他颜色),因为您使用的是填充形状。
  • geoms 的顺序很重要 - 后面的 geoms 排在最前面,所以移到geom_point()最后。
  • 增加stroke以增加点的边界大小

更新代码:

my_df %>% ggplot() +
    geom_line(aes(x = lastFinancingYear, y = raiseMedVal), size = 1.0, color = "#DDBB7B") +
    geom_line(aes(x = lastFinancingYear, y = foundMedVal), size = 1.0) +
    geom_point(aes(x = lastFinancingYear, y = raiseMedVal), size = 3.0, color = "#DDBB7B",
               shape = 21, 
               stroke = 2.0,
               fill = "white")
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明


MrG*_*ble 5

geom_pointline为这个确切的情况创造了(有一些天赋):

library(lemon)
library(tidyr)

my_df %>%
 gather(stat, val, raiseMedVal, foundMedVal) %>%
 ggplot(aes(lastFinancingYear, val, colour=stat)) + 
 geom_pointline(distance=0.1, fill='white', shape=21, size=3.5, stroke=2, linesize=2)
Run Code Online (Sandbox Code Playgroud)

请注意,我正在将数据帧更改为长格式,以便颜色链接到变量而不是硬编码.其次,美学在主要ggplot调用中复杂化以避免冗余设置.(我的apoligies distance必须是0.1,而不是0).

在此输入图像描述

要控制图例的颜色和外观,请使用常用的ggplot2函数,即scale_colour_manual(或_hue,或_brewer,或...).

编辑:哇,我学会了使用stroke控制点的边框宽度.谢谢@Marius.