【问题标题】:ggplot2 manual legend inside a plotggplot2 绘图内的手动图例
【发布时间】:2016-06-10 22:37:03
【问题描述】:

当我运行以下代码时,将创建一个密度图和直方图。我添加了两条垂直线来显示平均值和中位数。我想在绘图的右上角显示一个图例(带有红色虚线的“平均值”和带有绿色的“中值”)。您可以运行此代码,因为 df 在 R-studio 中已经可用。

ggplot(USArrests,aes(x=Murder)) + 
  geom_histogram(aes(y=..density..),binwidth=.5,col="black",fill="white") +
  geom_density(alpha=.2,fill="coral") +
  geom_vline(aes(xintercept=mean(Murder,na.rm=T)),color="red",linetype="dashed",size=1) +
  geom_vline(aes(xintercept=median(Murder,na.rm=T)),color="green",size=1) 

我的问题是我应该使用 theme() 还是其他东西在我的情节中显示图例?

【问题讨论】:

    标签: r plot ggplot2 legend


    【解决方案1】:

    不需要额外的data.frames。

    library(ggplot2)
    
    ggplot(USArrests,aes(x=Murder)) + 
      geom_histogram(aes(y=..density..),binwidth=.5,col="black",fill="white") +
      geom_density(alpha=.2,fill="coral") +
      geom_vline(aes(xintercept=mean(Murder,na.rm=TRUE), color="mean", linetype="mean"), size=1) +
      geom_vline(aes(xintercept=median(Murder,na.rm=TRUE), color="median", linetype="median"), size=1) +
      scale_color_manual(name=NULL, values=c(mean="red", median="green"), drop=FALSE) +
      scale_linetype_manual(name=NULL, values=c(mean="dashed", median="solid")) +
      theme(legend.position=c(0.9, 0.9))
    

    【讨论】:

      【解决方案2】:

      您最好创建一个额外的数据框来包含汇总统计信息 然后将其添加到情节中,而不是尝试手动创建 每个图例元素。图例位置可以用theme(legend.position = c())调整

      library("ggplot2")
      library("reshape2")
      library("dplyr")
      
      # Summary data.frame
      summary_df <- USArrests %>% 
                    summarise(Mean = mean(Murder), Median = median(Murder)) %>% 
                    melt(variable.name="statistic")
      
      # Specifying colors and linetypes for the legend since you wanted to map both color and linetype
      # to the same variable.
      
      summary_cols <- c("Mean" = "red", "Median" = "green")
      summary_linetypes <- c("Mean" = 2, "Median" = 1)
      
      
      ggplot(USArrests,aes(x=Murder)) + 
            geom_histogram(aes(y=..density..),binwidth=.5,col="black",fill="white") +
        geom_density(alpha=.2,fill="coral") +
        geom_vline(data = summary_df, aes(xintercept = value, color = statistic, 
                   lty = statistic)) +
        scale_color_manual(values = summary_cols) +
        scale_linetype_manual(values = summary_linetypes) +
        theme(legend.position = c(0.85,0.85))
      

      给予

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-20
        • 1970-01-01
        • 2016-08-05
        • 2015-08-02
        • 1970-01-01
        • 2013-02-28
        • 2017-07-22
        相关资源
        最近更新 更多