boyang
boyang

Reputation: 377

barplot using ggplot2

I have a data set like this:

cars    trucks  suvs
1          2    4
3          5    4
6          4    6
4          5    6
9          12   16

I'm trying to draw a bar chart for this data. Currently, I can do it with barplot:

barplot(as.matrix(autos_data), main="Autos", 
         ylab= "Total",beside=TRUE, col=rainbow(5))

Generating this graph:

Bar plot

So my questions are: Can I use ggplot2 to draw such a graph? Specifically - how do I use faceting or other options to split the graph by days of the week? If yes, how do I accomplish that? Additionally, how do I use facet to produce a different layout?

Upvotes: 17

Views: 32497

Answers (2)

Ben G
Ben G

Reputation: 4338

Here's with tidyr:

The biggest issue here is that you need convert your data to a tidy format. I highly recommend reading R for Data Science (http://r4ds.had.co.nz/) to get you up and running with tidy data and ggplot.

In general, a good rule of thumb is that if you have to enter multiple instances of the same geom, there's probably a solution in the format of your data which would enable you to put everything in the aes() function within the top level ggplot(). In this case you need to use the gather() to arrange your data appropriately.

library(tidyverse)

# I had some trouble recreating your data, so I just did it myself here
data <- tibble(type = letters[1:9], 
               repeat_1 = abs(rnorm(9)), repeat_2  
               =abs(rnorm(9)), 
               repeat_3 = abs(rnorm(9)))

data_gathered <- data %>%
  gather(repeat_number, value, 2:4)

ggplot(data_gathered, aes(x = type, y = value, fill = repeat_number)) +
geom_col(position = "dodge")

enter image description here

Upvotes: 0

Andrie
Andrie

Reputation: 179558

This has been asked many times before. The answer is that you have to use stat="identity" in geom_bar to tell ggplot not to summarise your data.

dat <- read.table(text="
cars    trucks  suvs
1   2   4
3   5   4
6   4   6
4   5   6
9   12  16", header=TRUE, as.is=TRUE)
dat$day <- factor(c("Mo", "Tu", "We", "Th", "Fr"), 
             levels=c("Mo", "Tu", "We", "Th", "Fr"))

library(reshape2)
library(ggplot2)

mdat <- melt(dat, id.vars="day")
head(mdat)
ggplot(mdat, aes(variable, value, fill=day)) + 
  geom_bar(stat="identity", position="dodge")

enter image description here

Upvotes: 35

Related Questions