Julien
Julien

Reputation: 9

How to make bar charts with names in abscissa?

I'm pretty new in R and I have an issue with bar charts.

I would like to create, with ggplot, bar charts where I have in abscissa names (such as "Luke", "Steven" and so on) and in ordinate their age (13, 14...). Nonetheless, I don't understand how to make such graphics because I can' t put in abscissa no-numerical elements. I saw a lot of people use bar charts to make count of a value, such as how many people have black hair, blue eyes... but not so many use bar charts to make a graphic with names (or same value types) in abscissa.

I aim at making a graphic like that : Example of the desired graphic type

I tried this code to solve my issue :

age <- c(12, 13, 19, 10)
persons <- c("Luke", "William", "George", "Steven")
df <- data.frame(age, persons)

library(ggplot2)
ggplot(data = df, mapping = aes(x = persons, y = age)) + geom_bar()

But I got this error :

Error in `geom_bar()`:
! Problem while computing stat.
ℹ Error occurred in the 1st layer.
Caused by error in `setup_params()`:
! `stat_count()` must only have an x or y aesthetic.

I know why I have this error but I don't have the solution of my problem.

If anybody would have an idea, it would be a pleasure!

Upvotes: 0

Views: 57

Answers (1)

stefan
stefan

Reputation: 123818

By default geom_bar computes the count which is mapped on the y (or x) aesthetic. That's why you get an error stat_count() must only have an x or y aesthetic.. If you want to make a bar chart with both a given x and y value use geom_col or the more verbose geom_bar(stat="identity"):

library(ggplot2)

ggplot(data = df, mapping = aes(x = persons, y = age)) + 
  geom_col()

Upvotes: 1

Related Questions