首页 文章

如何使用点的颜色填充geom_point图例中的框,而不仅仅是增加它们的大小?

提问于
浏览
4

我遇到了类似于here under "2- After having the two legends..."中描述的类似问题,但不是增加点大小(最终也会扩大图例本身),我想用相应的颜色填充图例中的每个框 . 就像在酒吧情节的传奇 . Data & code examples here .

通过这里查看其他几个问题,ggplot文档等,我尝试了我发现的代码片段的变体,但无法找到解决方案 . 图例始终保留点符号 .

因此:如果可能,如何调整或替换点/散点/气泡图的图例,使其看起来像条形图的图例?或者,更一般地说,如何将ggplot2中给定geom的图例替换为另一个geom的图例?谢谢你的任何提示!

Edit: Example with mtcars data

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point(aes(colour = factor(cyl), size = qsec))
p

添加我从其他SO-answers收集的内容......

p <- p + guides(colour = guide_legend(override.aes = list(fill = unique(mtcars$cyl))))
p

...保留点,而不是扩展颜色以填充图例框,无论我尝试使用guide()和list()的参数和数据源 .

另一方面:

ggplot(mtcars, aes(wt, mpg)) + geom_bar(aes(fill = factor(cyl)), stat="identity")

...在图例中绘制出色彩丰富的盒子 . 这就是我想要为泡沫情节做的事情 .

1 回答

  • 5

    您本身无法获得 fill 类型的图例,但您可以轻松模拟它:

    ggplot(mtcars, aes(wt, mpg)) + 
      geom_point(aes(colour = factor(cyl), size = qsec)) + 
      guides(col = guide_legend(override.aes = list(shape = 15, size = 10)))
    

    enter image description here

相关问题