K23
K23

Reputation: 29

geom_histogram (ggplot2): manually inputting values

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

Answers (1)

toldo
toldo

Reputation: 416

You are looking for stat = "identity". I used meltto 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")

enter image description here

Upvotes: 1

Related Questions