user8623559
user8623559

Reputation: 31

Add freq and place it in the graph

I am trying to get the variables of the freqs to add and put the total in the geom_bar. Right now the male and female freqs of the HairEyeColor data show on top of each other- no adding. Here's my code:

library(ggplot2)
hec = data.frame(HairEyeColor)
ggplot(hec, aes(Hair, Eye, fill=Freq)) + 
geom_bar(stat='identity',position= 'dodge') +
scale_fill_distiller(palette = "Spectral") +
geom_text(aes(label=Freq),position=position_dodge(width=0.9),vjust=-0.25)

It is not adding the male and female frequency. For example, there are 7 men and 7 women with red hair and green eyes. It shows only 7- or more likely it's showing both 7's on top of each other. That's why the brown /brown hair and eyes looks weird. There are 53 men and 66 women with the brown/brown.

I'd appreciate any help or suggestions.

Cheers.

Upvotes: 1

Views: 37

Answers (1)

Frank
Frank

Reputation: 98

It is not adding the values, because you program to use the values as is. You could remove the row sex and sum up the frequencies like this:

library(ggplot2)
hec = data.frame(HairEyeColor)

library(dplyr)

hec %<>%
  group_by(Hair, Eye) %>%
  summarise(Freq=sum(Freq))

ggplot(hec, aes(Hair, Eye, fill=Freq)) + 
  geom_bar(stat='identity',position= 'dodge') +
  scale_fill_distiller(palette = "Spectral") +
  geom_text(aes(label=Freq),position=position_dodge(width=0.9),vjust=-0.25)

Upvotes: 1

Related Questions