以下是在另一个软件中制作的图形的屏幕快照,该软件可在折线图的顶部创建散点图,并隐藏散点图所在的线。这就是我要在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)
...然后我得到一个看起来像这样的图:
存在散点标记并位于该行顶部的位置,但该行并未隐藏在标记的后面,并且散点标记也没有足够粗体/足够粗的标记。我不确定如何解决这些问题,我们将不胜感激!
提前谢谢!
答案 0 :(得分: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)
请注意,我正在将数据框更改为长格式,以使颜色链接到变量而不是硬编码。其次,在主ggplot
调用中混合了美学,以避免多余的设置。
(我的策略distance
必须为0.1,而不是0)。
要控制图例的颜色和外观,请使用常规的ggplot2函数,即scale_colour_manual
(或_hue
或_brewer
或...)。
编辑:哇,我了解了如何使用stroke
控制点的边框宽度。谢谢@Marius。
答案 1 :(得分:3)
您需要进行一些调整才能使其正常工作:
example("points")
来检查它们的形状,然后转到第3个图。fill = "white"
(或其他颜色)。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")
结果:
答案 2 :(得分:1)
变化很小但想法相同...
my_df %>% ggplot() +
geom_line(aes(x = lastFinancingYear, y = raiseMedVal), size = 0.8, color = "#DDBB7B") +
geom_point(aes(x = lastFinancingYear, y = raiseMedVal),
shape = 21, size = 1.0, stroke = 1.5, color = "#DDBB7B", fill = "white") +
geom_line(aes(x = lastFinancingYear, y = foundMedVal), size = 0.8) +
geom_point(aes(x = lastFinancingYear, y = foundMedVal),
shape = 21, size = 1.5, stroke = 1.5, color = "black", fill = "white")
如果您打算大量使用此格式,则可能需要创建一个函数来简化它。
spotted_lines <- function(x_var, y_var, my_color = "black") {
list(geom_line(aes(x = x_var, y = y_var), size = 0.8, color = my_color),
geom_point(aes(x = x_var, y = y_var), shape = 21, size = 1.0,
stroke = 1.5, color = my_color, fill = "white")
)
}
然后,您可以在ggplot调用中调用该函数,它将使直线和点成为几何图形,从而节省了时间并减少了出错的可能性。
my_df %>% ggplot() +
spotted_lines(x_var = my_df$lastFinancingYear, y_var = my_df$foundMedVal) +
spotted_lines(x_var = my_df$lastFinancingYear, y_var = my_df$raiseMedVal,
my_color = "#DDBB7B")