Skip to content

Instantly share code, notes, and snippets.

@rer145
Created November 6, 2017 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rer145/6444d8bab82824d6c35bf03cee84a2d2 to your computer and use it in GitHub Desktop.
Save rer145/6444d8bab82824d6c35bf03cee84a2d2 to your computer and use it in GitHub Desktop.
How to create a simple bar chart with ggplot2 in R
library(dplyr)
library(Lahman)
library(ggplot2)
# Get all the teams from 1980 and how many home runs they hit
df<-Teams %>%
filter(yearID==1980) %>%
select(name, HR) %>%
arrange(HR)
# Bar chat plot with the team name on the x-axis and number of HR on the y-axis
# We already summarized the HR totals in our above query, so stat="identity" is required
ggplot()+
geom_bar(data=df, aes(x=name,y=HR),stat="identity", color="green", fill="white")+
ggtitle("HR by team in 1980")
# Bar chat plot with the coordinates flipped, so team names are easier to read
ggplot()+
geom_bar(data=df, aes(x=name,y=HR),stat="identity", color="green", fill="white")+
ggtitle("HR by team in 1980")+
coord_flip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment