简体   繁体   English

ggplot2 - 包含两个数据集图例问题的线和点的图形

[英]ggplot2 - Graph with line and dots for two data sets legend issues

I'm graphing two data sets with ggplot. 我用ggplot绘制了两个数据集。 One should be a line, the other should be points. 一个应该是一条线,另一条应该是点。 I can get this working as below: 我可以这样工作如下:

d1 <- filter(d, variable==lineVar)
d2 <- filter(d, variable==dotVar)
g <- ggplot(d1, aes(clarity, x=xv, y=yv))
g <- g + geom_line(aes(colour=variable))
g <- g + ggtitle(title)
g <- g + xlab(xl)
g <- g + ylab(yl)
g <- g + geom_point(data=d2, size=4, aes(colour=variable))

输出ggplot2

The only issue is the legend! 唯一的问题是传说! As you can see, the "observed" data set has a line + point in the legend, when it really should just be a point. 正如您所看到的,“观察”数据集在图例中有一个线+点,当它真的应该只是一个点。 And reverse for "predicted", it should just be a line. 而对于“预测”反向,它应该只是一条线。

Is there some way to get a cleaner / more accurate legend? 有没有办法获得更清洁/更准确的传奇?

You can change the legend without changing the plot by using override.aes . 您可以使用override.aes更改图例而不更改绘图。 You didn't provide sample data, so I've used the built-in mtcars data frame for illustration. 您没有提供样本数据,因此我使用了内置的mtcars数据框进行说明。 The key line of code begins with guides . 代码的关键行以guides开头。 shape=c(16,NA) gets rid of one of the legend's point markers by setting its colour to NA . shape=c(16,NA)通过将其颜色设置为NA来消除其中一个图例的点标记。 linetype=c(0,1) gets rid of the other legend's line by setting its linetype to 0 . linetype=c(0,1)通过将其linetype设置为0来删除其他图例的行。 Also, you don't need to save the plot after each line of code. 此外,您不需要在每行代码后保存绘图。 Just add a + to each line and string them all together in a single statement, as in the example below. 只需在每行中添加一个+ ,并将它们全部串在一起,如下例所示。

library(reshape2)
library(ggplot2)

mtcars$mpg.line = mtcars$mpg
mtcars.m = melt(mtcars[,c("mpg","mpg.line","wt")], id.var="wt")
mtcars.m$variable = factor(mtcars.m$variable)

ggplot() +
  geom_line(data=mtcars.m[mtcars.m$variable=="mpg.line",],
             aes(wt, value, colour=variable), lwd=1) +
  geom_point(data=mtcars.m[mtcars.m$variable=="mpg",],
             aes(wt, value, colour=variable), size=3) +
  guides(colour=guide_legend(override.aes=list(shape=c(16,NA), linetype=c(0,1)))) +
  theme_grey(base_size=15)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM