2016-06-10 116 views
-1

當我運行下面的代碼時,將創建一個密度圖和直方圖。我添加了兩條垂直線以顯示平均值和中位數。我想在圖的右上角顯示一個圖例(紅色爲「Mean」,綠色爲「Median」)。您可以運行此代碼,因爲df已經在R-studio中可用。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=T)),color="red",linetype="dashed",size=1) + 
    geom_vline(aes(xintercept=median(Murder,na.rm=T)),color="green",size=1) 

我的問題是我應該使用theme()或其他在我的情節中顯示圖例嗎?

回答

0

您可能會更好地創建摘要統計 的附加data.frame,然後將其添加到該圖中,而不是試圖手動創建每個圖例元素的手動創建 。傳說位置可以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)) 

figure_with_legend

0

無需額外data.frame s爲單位進行調整。

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