簡體   English   中英

圖中的ggplot2手動圖例

[英]ggplot2 manual legend inside a plot

當我運行以下代碼時,將創建密度圖和直方圖。 我添加了兩條垂直線以顯示均值和中位數。 我想在圖的右上角顯示一個圖例(“ Mean”用紅色虛線表示,“ Median”用綠色)。 您可以運行此代碼,因為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()還是其他方式在圖中顯示圖例?

不需要額外的data.frame

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

您最好創建一個摘要統計信息的附加data.frame,然后將其添加到繪圖中,而不是嘗試手動創建每個圖例元素。 圖例位置可以通過theme(legend.position = c())進行調整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))

給予

fig_with_legend

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM