Eracog
Eracog

Reputation: 225

Geom bar graph and stat_count()

I would like to use a geom_bar for my data:

library(ggplot2)
p = ggplot(df, aes(x = word, y = freq)) + geom_bar(fill = "blue")
p + coord_flip() + labs(title = "Word frequency")

in data like this:

'data.frame':   953 obs. of  2 variables:
 $ word: Factor w/ 953 levels "music","play","movies playing",..: 75 70 81 405 291 455 192 470 22 269 ...
 $ freq: int  702 700 683 597 477 443 414 ...

but I receive this error for plot:

Error: stat_count() must not be used with a y aesthetic.

I found it is possible to use qplot which not using stat_count() but is there any way to use ggplot2?

Upvotes: 0

Views: 1417

Answers (1)

YCR
YCR

Reputation: 4002

Try with stat = "identity" :

library(ggplot2)
p = ggplot(df, aes(x = word, y = freq)) + geom_bar(stat = "identity", fill = "blue")
p + coord_flip() + labs(title = "Word frequency")

By default, geom_bar() compute the frequencies of the dataset.

If you want to have it ordered, use that code before to sort the levels of the factor word:

df$word <- factor(df$word, levels = df$word[order(df$freq)])

In your case, as you have a dataset of 953 words, may I suggest a word cloud? A barchart may not be the most appropriate, here, as your label will be stacked and unreadable.

Upvotes: 1

Related Questions