Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

r - Barchart of count of true/false values by group (dodged graphs)

I am rather new in R and ggplot. And I am not sure if what I want is doable.

Here is (a portion of) my data:

> mdf
   Batch     A     B     C     D     E
1      G FALSE  TRUE FALSE  TRUE FALSE
2      G FALSE FALSE FALSE  TRUE FALSE
3      G FALSE  TRUE FALSE FALSE FALSE
4      G FALSE FALSE FALSE  TRUE FALSE
5      G FALSE FALSE  TRUE  TRUE  TRUE
6      G FALSE FALSE  TRUE  TRUE  TRUE
7      G FALSE FALSE FALSE FALSE  TRUE
8      G FALSE FALSE  TRUE  TRUE  TRUE
9      G FALSE FALSE FALSE  TRUE FALSE
10     G FALSE FALSE FALSE  TRUE  TRUE
11     G FALSE FALSE FALSE FALSE  TRUE
12     G FALSE FALSE FALSE  TRUE FALSE
13     G FALSE FALSE FALSE  TRUE FALSE
14     G FALSE FALSE FALSE  TRUE FALSE
15     G FALSE FALSE FALSE  TRUE FALSE
16     G FALSE FALSE FALSE  TRUE FALSE
17     G FALSE FALSE  TRUE  TRUE FALSE
18     G FALSE FALSE  TRUE  TRUE  TRUE
19     A FALSE FALSE FALSE  TRUE  TRUE
20     A FALSE FALSE FALSE  TRUE  TRUE

where Batch can be any of A, B, G, R, S, and the other columns (A-E) are all boolean/logical values.

I was able to create a graph which counts the TRUE values in column B as follows: enter image description here

using:

ggplot(data = mdf, aes(x = Batch, y = as.numeric(B), fill = Batch))
    + stat_summary(fun.y = sum, geom = "bar")

Similarly, I can easily create 4 more graphs for the other columns (A, C, D, E).

But, is it possible to 'merge' these 5 graphs in a single graph? In other words, I would like a graph where I would have 5 groups (as in the above graph) for the 5 values of 'Batch', and in each group I would need a separate bar with the count of each of the 5 columns (A-E). Is this doable?

Update: Here is what I was looking for (created after using the suggestion from @mtoto) enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes it's possible, you just need to reshape your data first, then you can use position = "dodge" to draw a bar for each key. With tidyr:

library(tidyr)
library(dplyr)
library(ggplot2)

mdf %>% gather(key, value, -Batch) %>%
  ggplot(.,(aes(Batch, as.numeric(value), fill = key))) +
  stat_summary(fun.y = sum, geom = "bar", position = "dodge")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...