ggplot:手动添加图例以用于未映射的美学 [英] ggplot: Manually add legends for aesthetics that are not mapped

查看:77
本文介绍了ggplot:手动添加图例以用于未映射的美学的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个覆盖有点的条形图,其中两个点都有单独的图例.另外,我想使用aes()之外的参数选择条形的颜色和点的大小.由于两者均未映射,因此不会生成图例.

I want to produce a barplot overlayed with dots where both have separate legends. Also, I want to choose the color of the bars and the size of the dots using the arguments outside aes(). As both are not mapped, no legend is produced.

1)如何为填充和尺寸手动添加图例?

library(ggplot2)

d <- data.frame(group = 1:3,    
                prop = 1:3 )

ggplot(d, aes(x=group, y=prop)) +
  geom_bar(stat="identity", fill="red") +
  geom_point(size=5)

这就是我想出的:我使用了虚拟映射,然后根据需要修改了图例.但是这种方法对我来说显得笨拙.

This is what I came up with: I used dummy mappings and modified the legend according to my needs afterwards. But this approach appears clumsy to me.

2)是否有手动的说法:添加带有该标题,这些形状,这些颜色等的图例?

d <- data.frame(dummy1="d1",
                dummy2="d2",
                group = 1:3,    
                prop = 1:3 )


ggplot(d, aes(x=group, y=prop, fill=dummy1, size=dummy2)) +
  geom_bar(stat="identity", fill="red") +
  geom_point(size=5) +
  scale_fill_discrete(name="fill legend", label="fill label") +
  scale_size_discrete(name="size legend", label="size label")

以上,我将fill映射到dummy1.因此,我希望scale_fill_discrete会更改此图例.但是它似乎是在修改size图例.

Above I mapped fill to dummy1. So I would expect scale_fill_discrete to alter this legend. But it appears to modify the size legend instead.

3)我不确定这里出了什么问题.有什么想法吗?

推荐答案

我不确定您为什么说另外,我想使用aes()外部的参数选择条形的颜色和点的大小".是您正在尝试执行的操作,还是鉴于ggplot的工作原理必须执行的操作?

I'm not sure why you say "Also, I want to choose the color of the bars and the size of the dots using the arguments outside aes()". Is it something you're trying to do or is it something that you have to do given how ggplot works?

如果是后者,则一种解决方案如下-

If it's the latter, one solution is as under -

library(ggplot2)

d <- data.frame(group = 1:3,    
                prop = 1:3 )

ggplot(d, aes(x=group, y=prop)) +
    geom_bar(stat="identity",aes( fill="label")) +
    geom_point(aes(size='labelsize')) +
    scale_fill_manual(breaks = 'label', values = 'red')+
    scale_size_manual(breaks = 'labelsize', values = 5)

这篇关于ggplot:手动添加图例以用于未映射的美学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆