简体   繁体   中英

Add legend to overlapping histograms in ggplot2 R

I have the following plots

ggplot(No_Outliers)+ geom_histogram(aes(x=PVT_Pre_Correct), fill="aquamarine1", color="black", alpha=0.5) + 
geom_histogram(aes(x=PVT_Pre_Missed), fill="greenyellow", color="black",alpha=0.5) +  
geom_histogram(aes(x=PVT_Pre_Wrong),fill="mediumpurple3", color="black",alpha=0.5)

and I want to add a legend to it. Since there are three different histograms, ggplot2 doesn't have aes to merge from so, how do I create one from scratch of the fill colors?

What about gathering the data into a long format and then plotting?

# example data
No_Outliers <- iris[, 1:3]
colnames(No_Outliers) <- c("PVT_Pre_Correct", "PVT_Pre_Missed", "PVT_Pre_Wrong")

# make plot
library(tidyr)
library(ggplot2)
No_Outliers %>%
        gather(group, value, contains("PVT_Pre")) %>%
        ggplot(aes(x = value, fill = group)) +
        geom_histogram(alpha = 0.5, color = "black", position = "identity") +
        scale_fill_manual(values = c("aquamarine1", "greenyellow", "mediumpurple3"))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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