【问题标题】:Adding legend to barplot in ggplot在ggplot中向条形图添加图例
【发布时间】:2019-06-21 11:19:19
【问题描述】:

谁能告诉我如何在我的条形图中添加一个图例,它应该只包含一种颜色而不考虑多个组?由于我的图显示了四个不同的组激活了特定数量的调节策略,我只希望图例表明它是图表所有条形的“一般策略使用”表达。

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

【问题讨论】:

标签: r ggplot2 bar-chart legend


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多