ryry
ryry

Reputation: 86

How to plot a data frame with multiple frequencies for a factor?

I have this data frame:

df <- data.frame(make = c("dodge", "dodge", "toyota", "ford", "dodge", "toyota","toyota","ford",  "ford", "dodge"),
                  grn = c(    1,      1,        NA,      1,     NA,      NA,       1,         1,      NA,      NA),
                  blu = c(    NA,     NA,       1,       NA,    1,       NA,       NA,        NA,     1,       NA),
                  blk = c(    NA,     NA,       NA,      NA,    NA,      1,        NA,        NA,     NA,       1))   

I am trying to create a plot with "make" on the x-axis and the total "make" count for the y-axis and fill using the colors. I think I need to make a count table for the make and color but am unsure how to do this. For example the table would look something like this:

 DF <- read.table(text = "make  grn  blu  blk
                          dodge  2    1    1
                          ford   2    1    0
                          toyota 1    1    1", header = TRUE)

Then the solution is pretty straight forward

library(reshape2)
library(ggplot2)

DF1 <- melt(DF, id.var="make")

ggplot(DF1, aes(x = make, y = value, fill = variable)) +
geom_bar(stat = "identity")

So how can I transform my data frame "df" into "DF"?

Upvotes: 2

Views: 85

Answers (2)

echasnovski
echasnovski

Reputation: 1181

Well you don't have to make all these transformation. The shorter way of making plot:

df %>%
  gather(key=col, value=num, -make) %>%
  na.omit() %>%
  ggplot(aes(make, fill=col)) +
    geom_bar()

First three rows create the long form of the input data. Then it is passed to ggplot to make the statistical transformations for you.

Upvotes: 3

akuiper
akuiper

Reputation: 214957

You can use dplyr::summarise_all:

library(dplyr)
df %>% group_by(make) %>% summarise_all(sum, na.rm=TRUE)

# A tibble: 3 × 4
#    make   grn   blu   blk
#  <fctr> <dbl> <dbl> <dbl>
#1  dodge     2     1     1
#2   ford     2     1     0
#3 toyota     1     1     1

Upvotes: 2

Related Questions