Reputation: 29
Is there a way to input custom values for histogram heights for categorical variables in ggplot?
Given this example dataset
> example
category group
1: a blah
2: b blah
3: a blah
4: c blah
5: a blah
6: b ugh
7: a ugh
8: c ugh
9: b ugh
10: a ugh
11: b ugh
I can generate the following histogram
using the following code
ggplot(example, aes(x = category, fill = group)) + geom_histogram(position = 'dodge')
However, what if I had the following dataset of counts?
category blah.count ugh.count
1: a 3 2
2: b 1 3
3: c 1 1
How would I generate the same histogram as before directly (without recreating the previous dataset)?
I currently have a dataset where I have frequencies of certain categorical variables for different groups and I wish to plot a histogram comparing the frequencies of the categorical variables across the different groups.
Upvotes: 0
Views: 941
Reputation: 416
You are looking for stat = "identity"
. I used melt
to plot the two variables, but there might be another way.
category <- c("a", "b", "c")
blah.count <- c(3, 1, 1)
ugh.count <- c(2, 3, 1)
df <- data.frame(category, blah.count, ugh.count)
library(reshape2)
library(ggplot2)
df <- melt(df)
ggplot(data = df, aes(y = value, x = category, fill = variable)) +
geom_bar(stat = "identity", position = "dodge")
Upvotes: 1