将图例添加到ggplot中的barplot

时间:2019-01-28 12:41:06

标签: r ggplot2 bar-chart legend

有人可以告诉我如何在图例中添加仅由一种颜色组成但不考虑多个组的图例吗?由于我的绘图显示了四个激活了特定数量调节策略的不同组,因此我只希望图例通过图的所有条形表示它是“常规策略使用”表示。

id <- c(1,2,3,4)
group <- c (1,2,3,4)
means <- c(2.57, 2.32, 2.76, 2.61)
sds <- c(0.24, 0.21, 0.26, 0.24)
Problemtype <- c("No Problem", "Motivational Problem", "Knowledge Problem", "Both Problems")


barplot <- ggplot(df, aes(Problemtype, means)) + geom_bar(stat="identity", color="black", fill="lightblue") + geom_errorbar(aes(ymin = means - sds, ymax = means + sds), width=0.2)

barplot + labs(y="Overall Regulation (K 95%)", x = "Problemtype") + theme_classic()

1 个答案:

答案 0 :(得分:2)

首先,我添加了创建df的行。然后,我向df添加了一个新变量。我不确定这是否是您要的内容,但可以使用一种颜色添加图例。然后,您可以添加scale_fill_manual,以使用“ lightblue”进行绘制。希望能解决。

id <- c(1,2,3,4) 
group <- c (1,2,3,4)
means <- c(2.57, 2.32, 2.76, 2.61)
sds <- c(0.24, 0.21, 0.26, 0.24) 
Problemtype <- c("No Problem", "Motivational Problem", "Knowledge Problem", "Both Problems")
library(dplyr)

df <- data.frame(id = id, group = group, means = means, sds = sds,
Problemtype = Problemtype)
df['one_col'] = 'General Strategy Use'

barplot <- df %>%    
group_by(one_col) %>%   
ggplot( aes(Problemtype, means)) +    
geom_bar(stat="identity", aes( fill = one_col))+   
geom_errorbar(aes(ymin = means - sds, ymax = means + sds), width=0.2)

barplot + labs(y="Overall Regulation (K 95%)", x = "Problemtype") +   
theme_classic()+
scale_fill_manual(values = c("lightblue"))

plot1