0

I am trying to create a bar plot using fill to show multiple values within one bar. I am able to get totals (y value) per the x-value, but when I try to fill I just get the count.

Say the example data is a data frame named data:

State           Num.Class   Num.Tweets
Pennsylvania    C           98
Pennsylvania    P           10
Pennsylvania    E           174
Pennsylvania    S           70
Texas           C           233
Texas           P           42
Texas           E           30
Texas           S           26
California      C           57
California      P           32
California      E           39
California      S           20
Massachusetts   C           23
Massachusetts   P           74
Massachusetts   E           1
Massachusetts   S           3

Using ggplot I can get the totals:

ggplot(data) + aes(x=State, y = Num.Tweets) + geom_col()

enter image description here

When I try filling with gf_bar or ggplot() + geom_bar I get this instead of the four counts within one bar:

gf_bar(~ State, fill =~ Num.Tweets, data = data)

# or
ggplot()+
     geom_bar(aes(x = data$Num.Class, fill = data$Num.Tweets), color = "black" , position = "stack", show.legend = FALSE)

enter image description here

I've been looking at this post and others but don't see what I am missing. If I shift the variables I get an error or no output.

For example:

gf_bar(Num.Tweets ~ State, fill =~ Num.Class, data = data)

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

md2614
  • 353
  • 2
  • 14

1 Answers1

0

Is this what you're looking for?

library(ggplot2)
ggplot(data, aes(x=State, y = Num.Tweets, fill = Num.Class)) +
  geom_bar(stat = "identity")

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57