ggplot2中同一图例中的不同图例键 [英] Different legend-keys inside same legend in ggplot2
问题描述
假设我不需要适当的"变量映射,但仍希望使用图例键来帮助理解图表.我的实际数据类似于下面的df
Let's say I don't need a 'proper' variable mapping but still would like to have legend keys to help the chart understanding. My actual data are similar to the following df
df <- data.frame(id = 1:10, line = rnorm(10), points = rnorm(10))
library(ggplot2)
ggplot(df) +
geom_line(aes(id, line, colour = "line")) +
geom_point(aes(id, points, colour = "points"))
基本上,我希望与 points
相关的图例键是......只是一个点,中间没有线.我已经接近了这个:
Basically, I would like the legend key relative to points
to be.. just a point, without the line in the middle. I got close to that with this:
library(reshape2)
df <- melt(df, id.vars="id")
ggplot() +
geom_point(aes(id, value, shape = variable), df[df$variable=="points",]) +
geom_line(aes(id, value, colour = variable), df[df$variable=="line",])
但它定义了两个单独的图例.修复第二个代码(并且必须重塑我的数据)也可以,但我更喜欢一种方法(如果有的话)来手动更改任何图例键(并继续使用第一个方法).谢谢!
but it defines two separate legends. Fixing the second code (and having to reshape my data) would be fine too, but I'd prefer a way (if any) to manually change any legend key (and keep using the first approch). Thanks!
感谢@alexwhan,你让我想起了变量映射.但是,到目前为止,我最简单的方法仍然是以下(非常糟糕的黑客!):
thanks @alexwhan you refreshed my memory about variable mapping. However, the easiest way I've got so far is still the following (very bad hack!):
df <- data.frame(id = 1:10, line = rnorm(10), points = rnorm(10))
ggplot(df) +
geom_line(aes(id, line, colour = "line")) +
geom_point(aes(id, points, shape = "points")) +
theme(legend.title=element_blank())
这只是隐藏了两个不同图例的标题.
which is just hiding the title of the two different legends.
欢迎其他想法!!!
推荐答案
您可以在 guides()
函数中使用 override.aes=
来更改图例的默认外观.在这种情况下,您的指南是 color=
然后您应该设置 shape=c(NA,16)
以删除线的形状,然后 linetype=c(1,0)
从点删除线.
You can use override.aes=
inside guides()
function to change default appearance of legend. In this case your guide is color=
and then you should set shape=c(NA,16)
to remove shape for line and then linetype=c(1,0)
to remove line from point.
ggplot(df) +
geom_line(aes(id, line, colour = "line")) +
geom_point(aes(id, points, colour = "points"))+
guides(color=guide_legend(override.aes=list(shape=c(NA,16),linetype=c(1,0))))
这篇关于ggplot2中同一图例中的不同图例键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!