简体   繁体   English

向ggplot2 R中的重叠直方图添加图例

[英]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? 由于存在三种不同的直方图,因此ggplot2不会合并aes,如何从零开始创建一个填充颜色?

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

在此处输入图片说明

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

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