Liondancer
Liondancer

Reputation: 16479

Displaying bar plot in R

I am trying to create a barplot with midwest dataset. However, when I run the code, I do not see anything in my plots window

library(ggplot2)
try(data('midwest',package='ggplot2'))
for (s in unique(midwest$state)) {
  state_data = subset(midwest, state == s)
  ggplot(state_data, aes(x=county, y=percprof)) + geom_bar(stat='identity')
}

Upvotes: 0

Views: 58

Answers (2)

C-x C-c
C-x C-c

Reputation: 1321

This is a great opportunity for facetting, rather than using a for loop, if you'd rather have them on one figure. Try:

ggplot(midwest) +
geom_bar(aes(county, percprof), stat = "identity") +
facet_wrap(~state)

You'll have to play with the x axis to get it to read clearly..

Upvotes: 2

Roman Luštrik
Roman Luštrik

Reputation: 70653

You will need to print the object explicitly. If you're using Rstudio, you can flip through the resulting plots using left and right arrow button.

for (s in unique(midwest$state)) {
  state_data = subset(midwest, state == s)
  print(
    ggplot(state_data, aes(x=county, y=percprof)) + geom_bar(stat='identity')
  )
}

Upvotes: 3

Related Questions