我想提出一种不需要修改数据框的解决方案,它很直观(一旦您考虑了图层的绘制方式),并且不涉及相互覆盖的线条。但是,它确实有一个问题:它不允许您修改线型。我不知道为什么会这样,所以如果有人能插话来启发我们,那就太好了。
对OP的快速回答:
ggplot(df, aes(x = date, y = value, color = adjuster))+
geom_line(aes(group = 1, colour = adjuster))+
geom_point(aes(group = adjuster, color = adjuster, shape = adjuster))
在 OP 的数据框中,可以group=1
用来创建一个跨越整个时期的组。
用数字说明的例子:
# Create data
df <- structure(list(year = c(1990, 2000, 2010, 2020, 2030, 2040),
variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "Something", class = "factor"),
value = c(4, 5, 6, 7, 8, 9), category = structure(c(1L, 1L, 1L,
2L, 2L, 2L), .Label = c("Observed", "Projected"), class = "factor")), .Names = c("year",
"variable", "value", "category"), row.names = c(NA, 6L), class = "data.frame")
# Load library
library(ggplot2)
与 OP 相似的基本图按category
insidegeom_point(aes())
和 inside对数据进行分组geom_line(aes())
,在此应用程序中,该线不会“桥接”两个类别的两个点。
# Basic ggplot with geom_point() and geom_line()
p <- ggplot(data = df, aes(x = year, y = value, group = category)) +
geom_point(aes(colour = category, shape = category), size = 4) +
geom_line(aes(colour = category), size = 1)
ggsave(p, file = "ggplot-points-connect_p1.png", width = 10, height = 10)
我的解决方案的关键是按内部分组variable
但按category
内部着色geom_line(aes())
# Modified version to connect the dots "continuously" while preserving color grouping
p <- ggplot(data = df, aes(x = year, y = value)) +
geom_point(aes(group = category, colour = category, shape = category), size = 4) +
geom_line(aes(group = variable, colour = category), size = 1)
ggsave(p, file = "ggplot-points-connect_p2.png", width = 10, height = 10)
然而,遗憾的是,据我所知,目前无法通过这种方法控制线型:
ggplot(data = df, aes(x = year, y = value)) +
geom_point(aes(group = category, colour = category, shape = category), size = 4) +
geom_line(aes(group = variable, colour = category), linetype = "dotted", size = 1)
## Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line
备注:我正在使用另一个数据框,因为我正在从我正在做的事情中复制粘贴,这让我访问了这个问题——这样我就可以上传我的图像。