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
<
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")
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")