ggplot2手册内的图例

时间:2016-06-10 22:37:04

标签: r plot ggplot2 legend

当我运行以下代码时,将创建密度图和直方图。我添加了两条垂直线来显示平均值和中位数。我想在图的右上角显示一个图例(带有红色的“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()或其他东西在我的情节中显示图例吗?

2 个答案:

答案 0 :(得分:1)

无需额外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))

答案 1 :(得分: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