Pregunta

I'm trying to take a dataframe and plot it with ggplot like so:

library(ggplot2)
success<-sample(1:10,30,replace=TRUE)
animal<-rep(c("cat","dog","bird"),each=10)
trick<-sample(letters[1:10],30,replace=TRUE)

data.plot<-data.frame(success,animal,trick)

ggplot(data.plot,aes(y=success,x=trick,fill=animal))+geom_bar(stat="identity") + theme(axis.text.x = element_text(angle=90))

I'm trying to get the scaling to be relative, though (0-100%) for each bar. This would imply that each bar is the same height (100%), but the colors are divided into the relative proportions of their weight in the total sum of all the observations in each bar on the graph.

Any ideas how to do this?

¿Fue útil?

Solución

Like this?

library(dplyr)
data.plot2 <- data.plot %.% 
  group_by(trick) %.%
  mutate(success_rel = success / sum(success) * 100)
ggplot(data.plot2,aes(y=success_rel,x=trick,fill=animal))+geom_bar(stat="identity") + theme(axis.text.x = element_text(angle=90))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top