繁体   English   中英

ggplot2图例,用于结合geom_bar和geom_point的绘图

[英]ggplot2 legend for plot combining geom_bar and geom_point

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

产生具有类似结构的数据框:

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用作“虚拟”美学,只是为了获得图例。

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

# 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设置shape=NULL使形状图例没有标题。

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()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM