ggplot2图例,用于结合geom_bar和geom_point的绘图 [英] ggplot2 legend for plot combining geom_bar and geom_point

查看:180
本文介绍了ggplot2图例,用于结合geom_bar和geom_point的绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绘制一个图以条形图显示投资组合中各种证券的回报,然后将点叠加在指示这些证券敞口的条形上方.但是,我得到的图例完全忽略了这些点,只绘制了条形图.

I am trying to make a plot to show the returns of various securities in a portfolio in a bar plot and then superimpose points over the bars indicating exposure to those securities. However, the legend I get completely ignores the points and only draws a legend for the bars.

out<-data.frame(security=c("A", "B", "C", "D", "A", "B", "C", "D"), avg_weight=c(0.1,0.2,0.3,0.4, 0.1, 0.2, 0.3, 0.4), return_type=c(rep("systematic",4), rep("idiosyncratic",4)), return=rnorm(8))

现在,用于绘图

g <- ggplot(data=out, aes(x=factor(security, levels=out$security), y=return))
g <- g + geom_bar(stat="identity", position="dodge", aes(fill=return_type))
g <- g + geom_point(aes(x=factor(security, levels=out$security), y=avg_weight))
g <- g + ggtitle("Systematic and Idiosyncratic Returns")
g <- g + theme(axis.text.x=element_text(angle=70, hjust=1))
g + xlab("Security Description") + ylab("Return")

  • 曝光

推荐答案

ggplot仅在aes内部创建美观映射时才会生成图例.通常,这是通过将数据列映射到美学来完成的,例如fillshapecolor.在这里,我们实际上并不想将avg_weight映射到美学,因此我们将shape用作虚拟"美学,只是为了获得图例.

ggplot generates legends only when you create an aesthetic mapping inside aes. This is usually done by mapping a data column to an aesthetic, like fill, shape, or color. Here we don't actually want to map avg_weight to an aesthetic, so we'll use shape as a "dummy" aesthetic, just to get the legend.

首先,为数据可重复性设置种子:

First, set a seed for data reproducibility:

# Set a seed for reproducibility
set.seed(4)
out<-data.frame(security=c("A", "B", "C", "D", "A", "B", "C", "D"), 
                avg_weight=c(0.1,0.2,0.3,0.4, 0.1, 0.2, 0.3, 0.4), 
                return_type=c(rep("systematic",4), rep("idiosyncratic",4)), return=cumsum(rnorm(8,0,0.1)))

在下面的代码中,我们向geom_point添加了虚拟"形状美感,以便生成形状图例.然后在labs中设置shape=NULL,以使形状图例没有标题.

In the code below, we add a "dummy" shape aesthetic to geom_point so that a shape legend will be generated. Then in labs we set shape=NULL so that the shape legend won't have a title.

ggplot(data=out, aes(x=security)) + 
  geom_bar(stat="identity", aes(y=return, fill=return_type, group=return_type), position="dodge") +
  geom_point(aes(y=avg_weight, shape="Exposure")) + 
  ggtitle("Systematic and Idiosyncratic Returns") +
  theme(axis.text.x=element_text(angle=70, hjust=1)) +
  labs(x="Security Description", y="Return", shape=NULL) +
  theme_classic()

这篇关于ggplot2图例,用于结合geom_bar和geom_point的绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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