我正在尝试使用 ggplot 在 R 中绘制 2 组数据点和一行。
我遇到的问题是传说。
从附图中可以看出,图例将线条应用于所有 3 个数据集,即使其中只有一个用线条绘制。
我已经将数据融合到一个长帧中,但这仍然需要我为每个对 geom_line()
的单独调用过滤数据集。和 geom_path()
.
我想绘制融化的数据,根据一个数据集绘制一条线,并在其余两个上点,并带有完整的图例。
这是我编写的用于生成绘图的示例脚本:
xseq <- 1:100
x <- rnorm(n = 100, mean = 0.5, sd = 2)
x2 <- rnorm(n = 100, mean = 1, sd = 0.5)
x.lm <- lm(formula = x ~ xseq)
x.fit <- predict(x.lm, newdata = data.frame(xseq = 1:100), type = "response", se.fit = TRUE)
my_data <- data.frame(x = xseq, ypoints = x, ylines = x.fit$fit, ypoints2 = x2)
## Now try and plot it
melted_data <- melt(data = my_data, id.vars = "x")
p <- ggplot(data = melted_data, aes(x = x, y = value, color = variable, shape = variable, linetype = variable)) +
geom_point(data = filter(melted_data, variable == "ypoints")) +
geom_point(data = filter(melted_data, variable == "ypoints2")) +
geom_path(data = filter(melted_data, variable == "ylines"))
pushViewport(viewport(layout = grid.layout(1, 1))) # One on top of the other
print(p, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
![Resulting plot from the sample code above](https://i.sstatic.net/jSd7x.png)
最佳答案
您可以像这样手动设置它们:
我们为第一项设置 linetype = "solid",为其他项设置 "blank"(无线)。
同样,对于第一项,我们不设置形状 (NA),而对于其他项,我们将设置我们需要的任何形状(例如,我只是将 7 和 8 放在那里)。见例如http://www.r-bloggers.com/how-to-remember-point-shape-codes-in-r/帮助您选择适合您需要的正确形状。
如果你对点很满意,那么你可以使用 my_shapes = c(NA,16,16)
和 scale_shape_manual(...)
不需要。
my_shapes = c(NA,7,8)
ggplot(data = melted_data, aes(x = x, y = value, color=variable, shape=variable )) +
geom_path(data = filter(melted_data, variable == "ylines") ) +
geom_point(data = filter(melted_data, variable %in% c("ypoints", "ypoints2"))) +
scale_colour_manual(values = c("red", "green", "blue"),
guide = guide_legend(override.aes = list(
linetype = c("solid", "blank","blank"),
shape = my_shapes))) +
scale_shape_manual(values = my_shapes)
![enter image description here](https://i.sstatic.net/4WHI1.png)
但是我很好奇是否有一些更自动化的方式。希望有人可以发布更好的答案。
这篇文章非常依赖这个答案:ggplot2: Different legend symbols for points and lines
关于r - 使用ggplot在R中分别绘制点和线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32009346/