简体   繁体   English

图中的ggplot2手动图例

[英]ggplot2 manual legend inside a plot

When I run the below code, a density plot and histogram will be created. 当我运行以下代码时,将创建密度图和直方图。 I've added two vertical line to show mean and median. 我添加了两条垂直线以显示均值和中位数。 I want to display a legend ("Mean" with dotted red and "Median" with green color) at the top-right corner of the plot. 我想在图的右上角显示一个图例(“ Mean”用红色虚线表示,“ Median”用绿色)。 You can run this code as the df is already available in R-studio. 您可以运行此代码,因为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) 

My question is shall I use theme() or something else to display legend in my plot? 我的问题是我应该使用theme()还是其他方式在图中显示图例?

No need for extra data.frame s. 不需要额外的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))

You're probably better off creating an additional data.frame of the summary statistics and then adding this to the plot instead of trying to fiddle around with manually creating each legend element. 您最好创建一个摘要统计信息的附加data.frame,然后将其添加到绘图中,而不是尝试手动创建每个图例元素。 Legend position can be adjusted with theme(legend.position = c()) 图例位置可以通过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))

giving 给予

fig_with_legend

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

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