【问题标题】:ggplot2 legend for plot combining geom_bar and geom_pointggplot2 图例结合 geom_bar 和 geom_point
【发布时间】:2017-11-29 22:46:04
【问题描述】:

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

生成具有相似结构的数据框:

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

如何在图例中获得第三个条目,例如:

  • 曝光

【问题讨论】:

    标签: r ggplot2 tidyr


    【解决方案1】:

    只有当您在aes 中创建美学映射时,ggplot 才会生成图例。这通常通过将数据列映射到美学来完成,例如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,这样形状图例就没有标题了。

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

    【讨论】:

    • 感谢eipi10,非常神秘! :)
    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多