在ggplot2 R中为重叠直方图添加图例

问题描述 投票:0回答:1

我有以下情节

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)

我想为它添加一个图例。由于有三种不同的直方图,ggplot2没有合并的,所以如何从头开始创建填充颜色?

r ggplot2
1个回答
0
投票

那么将数据收集成长格式然后绘图呢?

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.