繁体   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