R图例只显示第一项

R legend only showing first item

这是我的 R 代码,下面是结果图。

ggplot(Data,aes(x=P, y=T, colour=Study , fill=Method, shape=Direction)) 
+ geom_point(size=2, alpha=0.5) 
+ scale_shape_manual(values=c(22,23,24),labels=c("1","2","3")) 
+ scale_colour_manual(values=cp2,labels=cp2) 
+ scale_fill_manual(values=c("white","black"),labels=c("1","2"))

为什么图例只显示第一个形状值而显示不正确的填充值(第二个应该为空)?

此外,我应该使用 discrete 而不是 manual 吗?

(我在 64 位上使用 RStudio 版本 0.98.1091 和 R 版本 3.1.2 Windows 7)

EDIT 我现在意识到符号在导出的图像中正确显示(我没有注意到!)...只有在 RStudio 中符号才不起作用(填充问题仍然存在,但已使用下面 Ben Bolker or lukeA 的答案解决)。

这个(可重现的)示例通过使用 guide_legend()override.aesfill 图例的点类型设置为实际使用填充背景的点类型,从而使您到达那里。对于您的其他问题,如果您能阐明您对 shape(在本例中为 gear)图例的期望,将会有所帮助。

加载包:

library("ggplot2")

修改内置mtcars数据框:

mm <- transform(mtcars,
                am=factor(am),
                gear=factor(gear),
                carb=factor(carb>1),
                cyl=factor(cyl))
theme_set(theme_classic())  ## blank background

ggplot(mm,
       aes(x=wt, y=mpg, colour=cyl,
           fill=carb, shape=gear))+
             geom_point(size=2, alpha=0.5)+
               scale_shape_manual(values=c(22,23,24))+
               scale_fill_manual(values=c("white","black"),
                   guide=guide_legend(override.aes=list(shape=22)))

您可以通过使用 override.aes:

操纵图例来覆盖这种奇怪的行为
library(ggplot2)
df <- data.frame(x = runif(12), y = runif(12), fill = gl(2, 6), colour = gl(4, 3), shape = gl(3, 4))
ggplot(df, aes(x, y, fill = fill, colour = colour, shape = shape)) + 
  scale_fill_manual(values=c("white","black"),labels=c("1","2")) +
  geom_point(size=10, alpha=0.5) + 
  scale_shape_manual(values=c(22,23,24),labels=c("1","2","3")) + 
  guides(shape = guide_legend(override.aes = list(alpha = 1)), 
         fill = guide_legend(override.aes = list(colour = c("black", "white"))))