简体   繁体   English

如何使用ggplot制作条形图,使用多个列作为x轴?

[英]How to make a bar plot using ggplot that uses multiple columns for the x-axis?

I am trying to use multiple column names as the x-axis in a barplot. 我试图在一个条形图中使用多个列名作为x轴。 So each column name will be the "factor" and the data it contains is the count for that. 因此,每个列名称将是“因子”,它包含的数据是该数量的计数。

I have tried iterations of this: 我尝试过迭代:

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

I tried concatenating the x values I want to show with aes(c(col1, col2)) but the aesthetics length does not match and won't work. 我尝试连接我要用aes(c(col1, col2))显示的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

Both of these failed (kind of expected based on aes length error code), but hopefully you know the direction I was aiming for and can help out. 这两个都失败了(基于aes长度错误代码预期的那种),但希望你知道我的目标并且可以提供帮助。

Goal is to have 4 separate groups, each with their own boxplot (1 for every response). 目标是拥有4个独立的小组,每个小组都有自己的箱形图(每个响应都有1个)。 And also have them faceted by week. 并且还让他们在一周之内受到影响。

Using the simple code below got mostly what I want. 使用下面的简单代码主要得到我想要的。 Unfortunately I don't think it would be as easy to include the points and other characteristics to the plot like you can with ggplot. 不幸的是,我不认为像ggplot那样容易将点和其他特征包含在情节中。

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

And I could pretty easily just filter by the different weeks and use mfrow for faceting. 而且我可以很容易地在不同的星期过滤并使用mfrow进行刻面。 Not as informative as ggplot, but gets the job done. 不像ggplot那样提供信息,但可以完成工作。 If anyone else has other workarounds, I'd be interested in seeing. 如果其他人有其他解决方法,我会有兴趣看到。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM