Confused about geom_bar. Keep getting "can only have an x or y aesthetic" error

Trying to use ggplot to plot the distribution of the name John in the babynames library. Use geom_bar, geom_line, and facet_wrap to separate females and males.

library(babynames)
library(dplyr)
library(ggthemes)
library(ggrepel)
library(ggplot2)

selected_name <- babynames %>%
filter(name %in% "John")
ggplot1= selected_name %>% ggplot(mapping = aes(x= year, y=n))

ggplot1 + geom_bar(width = 0.1)

1 Like

For geom_bar() you need put only one variable x or y, not the both. For others plots you could use x and y variables.

library(babynames)
library(dplyr)
library(ggthemes)
library(ggrepel)
library(ggplot2)

selected_name <- babynames %>%
  filter(name %in% "John")

### geom_col
ggplot(selected_name, aes(x= year, y=n)) +
  geom_col( color= '#ABE164')+
  labs(title='your title') +
  facet_wrap( ~ sex)

#### geom_line
ggplot(selected_name, aes(x= year, y=n)) +
  geom_line( color= '#99230A')+
  labs(title='your title') +
  facet_wrap( ~ sex)

1 Like

Thank you. I got it to work with geom_bar(stat = "identity")
and added scales= "free" in the facet_wrap

1 Like

Hi,
I would like to draw your attention to a very useful resource for the plotting with ggplot2: R Graphics Cookbook written by Winston Chang.
This book is also available online.
This chapter in particular can be of interest to you. It is dedicated to the two ways of implementing bar/column graphs in ggplot2 which explains the case for use of geom_bar() and/or geom_col().
I personally find the book's examples, ready to use recipes, and comparisons with base R plotting functions very useful to understand the ggplot2 philosophy.

Vladimir
The curious mechanobiologist

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.