首页 > 解决方案 > 如何使用 ggplot 制作条形图,其中 x 轴使用多列?

问题描述

我正在尝试使用多个列名作为条形图中的 x 轴。因此,每个列名都是“因素”,它包含的数据就是它的计数。

我已经尝试过这样的迭代:

 ggplot(aes( x = names, y = count)) + geom_bar()

我尝试连接我想要显示的 x 值,aes(c(col1, col2)) 但美学长度不匹配并且不起作用。

library(dplyr)
library(ggplot2)
head(dat)

  Sample Week Response_1 Response_2 Response_3 Response_4 Vaccine_Type
1      1    1        300          0       2000        100            1
2      2    1        305          0        320         15            1
3      3    1        310          0        400         35            1
4      4    1        400          1        410         35            1
5      5    1        405          0        180         35            2
6      6    1        410          2        800         75            2


 dat %>%
  group_by(Week) %>%
  ggplot(aes(c(Response_1, Response_2, Response_3, Response_4)) +
  geom_boxplot() +
  facet_grid(.~Week)

dat %>%
  group_by(Week) %>%
  ggplot(aes(Response_1, Response_2, Response_3, Response_4)) +
  geom_boxplot() +
  facet_grid(.~Week)

> Error: Aesthetics must be either length 1 or the same as the data
> (24): x

这两个都失败了(基于 aes 长度错误代码的预期),但希望您知道我的目标方向并可以提供帮助。

目标是有 4 个独立的组,每个组都有自己的箱线图(每个响应 1 个)。并且还要按周对它们进行刻面。

标签: rggplot2aesthetics

解决方案


使用下面的简单代码主要是我想要的。不幸的是,我认为将点和其他特征包含在情节中并不像使用 ggplot 那样容易。

boxplot(dat[,3:6], use.cols = TRUE)

而且我可以很容易地按不同的周过滤并使用 mfrow 进行刻面。不如 ggplot 提供的信息丰富,但可以完成工作。如果其他人有其他解决方法,我很想看看。

在此处输入图像描述


推荐阅读