Dr. Fabian Habersack
Dr. Fabian Habersack

Reputation: 1141

Plot one value per group instead of summing values up using ggplot's bar_plot()

I'm sure this is covered somewhere by a post, but I couldn't find it. The problem is that I want to plot a single variable's values for each group in my dataset.

This is my data:

my.data <- data.frame(
  a=c("aa","aa","bb","bb","cc","cc"),
  b=c(1,1,4,4,9,9)
)

Using {ggplot2}, I tried this:

ggplot(my.data, aes(x=a, y=b)) + geom_bar(stat="identity")

However, judging from the resulting plot, I only get the sum of the values per group instead of the value itself. So what this yields is 2 (for "aa"), 8 (for "bb") and 18 (for "cc").

I also tinkered around with group- and mean() commands, but it didn't work. Does anyone know a quick fix?

Upvotes: 1

Views: 567

Answers (1)

markus
markus

Reputation: 26373

Two options that come to my mind:

1) call unique on my.data

ggplot(unique(my.data), aes(x=a, y=b)) + 
  geom_bar(stat="identity")

2) use stat_summary which "operates on unique x"

ggplot(my.data, aes(x=a, y=b)) + 
  stat_summary(geom = "bar", fun.y = 'identity')

Result

enter image description here

Upvotes: 4

Related Questions