Dhiraj
Dhiraj

Reputation: 1710

Trouble with plotting using ggplot2

I am using dplyr and ggplot2 to make some sense out of data that I have on hospitals. I'm use the following code to get Ownership of hospitals and their performance in percentage from my tidied data (a data frame called "final):

owner <- final%>%  group_by(Ownership)%>%  summarise(Score=mean(Total))

This produces

> owner
Source: local data frame [4 x 2]

     Ownership    Score
1          HMO 78.84817
2 governmental 84.33656
3    municipal 81.40438
4 semi private 85.01617

I can plot the above using

p <- ggplot(owner, aes(Ownership, Score))
p+geom_bar(stat="identity")

I can't post images as I need at least 10 reputations!

I can also classify hospitals based on their sizes :

owner <- final%>%
group_by(Ownership, Size)%>%
summarise(Score=mean(Total))

which gives me this

> owner
Source: local data frame [10 x 3]
Groups: Ownership

      Ownership   Size    Score
1           HMO    big 82.50567
2           HMO medium 83.12919
3           HMO  small 67.76271
4  governmental    big 85.86831
5  governmental medium 83.70145
6  governmental  small 84.69767
7     municipal    big 81.40438
8  semi private    big 94.07850
9  semi private medium 82.54112
10 semi private  small 84.33079

What I am now trying to do is plot the same data as the first one, but filled in the percentages of size :

p <- ggplot(owner, aes(Ownership, Score, fill=Size))
  p+geom_bar(stat="identity")

This plot is obviously wrong as I what I am expecting is breakdown of the original value, for eg. for HMO it is 78.84817, in terms of Size percentages. Can someone help me with this please.

Upvotes: 0

Views: 103

Answers (1)

rnso
rnso

Reputation: 24535

Try:

library(data.table)
setDT(owner)[,meanscore:=mean(Score),by=Ownership][]
owner[,percentscore:=meanscore*Score/sum(Score),by=Ownership][]
ggplot(owner, aes(Ownership, percentscore, fill=Size)) + geom_bar(stat="identity")

enter image description here

Upvotes: 2

Related Questions