r - 在 ggplot 中向 barplot 添加图例

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

最佳答案

首先,我添加了创建 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

关于r - 在 ggplot 中向 barplot 添加图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54402265/

相关文章:

r - 如何在文档中定义自定义 CSS?

r - 条形图 ggplot : conflict between values on bar and x axis label

r - dplyr::select 自制函数中未找到对象

android - MPAndroid 图表未显示 xAxis 的任何标签,缺少什么?

r - 将由left_join()产生的所有列前缀为原始表名

r - testthat:处理警告和值

r - 在 ggplot2 中使用闪避条形图绘制相对频率

android - 如何正确显示AChartEngine条形图

python - 使用 Matplotlib.pyplot 在 python 中绘制条形图

r - 如何在R中批量查询Id的数量