R语言 条形图,每组2条

bttbmeg0  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(131)

我想用分组变量x的每个值分别绘制mean_1mean_2。因此,每组需要两个条形图。
数据类型:

n <- 100
set.seed(123)  
data <- data.frame(
  x = round(runif(n, min = 3, max = 5)),
  mean_1 = rnorm(n, mean = 0, sd = 1),
  mean_2 = rnorm(n, mean = 0, sd = 1) + 0.3)

字符串
仅显示1条的方法:

library(ggplot2)

ggplot(data, aes(x = factor(x))) +
  geom_bar(aes(y = mean_1), stat = "identity") +
  geom_bar(aes(y = mean_2), stat = "identity") +
  labs(x = "x",
       y = "Abs") +
  scale_fill_manual(values = c("blue", "red")) +
  theme_minimal()


谢谢你

r8uurelv

r8uurelv1#

您应该首先使用tidyr::pivot_longer(或任何您喜欢的reshaping approaches)整理数据集,然后使用ggplot,并对现有代码进行一些调整(见下文)数据

data_long <- tidyr::pivot_longer(data, mean_1:mean_2, 
                                 names_to = "mean", 
                                 values_to = "value")
#       x mean     value
#   <dbl> <chr>    <dbl>
# 1     4 mean_1  0.253 
# 2     4 mean_2  1.09  
# 3     5 mean_1 -0.0285
# 4     5 mean_2  1.07  
# ....

字符串
要进行绘图,请在aes()中使用y = valuefill = mean,以及在geom_bar中使用position = position_dodge()

ggplot(data_long, aes(x = factor(x), y = value, fill = mean)) +
  geom_bar(stat = "identity",  position = position_dodge()) +
  labs(x = "x",
       y = "Abs") +
  scale_fill_manual(values = c("blue", "red")) +
  theme_minimal()


x1c 0d1x的数据
上面的图显示了mean_1mean_2的范围,所以如果这是可视化的目标,那么你已经准备好了。但是,对于这些数据,你可能更好地使用geom_boxplot,它通过盒子,胡须和点按组显示几个汇总统计数据:

ggplot(data_long, aes(x = factor(x), y = value, fill = mean)) +
  geom_boxplot() +
  labs(x = "x",
       y = "Abs") +
  scale_fill_manual(values = c("blue", "red")) +
  theme_minimal()



正如@AllanCameron提到的,你可能想看看... + geom_bar( stat = "summary", fun = mean, ...) + ...,它计算并绘制每个mean_1mean_2的平均值:

ggplot(data_long, aes(x = factor(x), y = value, fill = mean)) +
  geom_bar(stat = "summary", fun = mean, position = position_dodge()) +
  labs(x = "x", y = "Abs") +
  scale_fill_manual(values = c("blue", "red")) +
  theme_minimal()


这将产生以下图:

相关问题