Reputation: 401
I'm trying to produce a stacked bar chart in R using the data-frame (df) given below. The chart needs be to be scaled to show proportions rather than absolute values. The idea is to have TiA and CvSS on the x-axis and the bars divide by the proportions which each region takes up for TiA and CvSS respectively.
Does anyone know how to achieve this using ggplot2?
Region <- c("A", "B", "C")
TiA <- c(2065.8408, 1020.1331, 742.8428)
CvSS <- c(1.549020, 1.422771, 1.174165)
df <- data.frame(Region, TiA, CvSS)
Upvotes: 0
Views: 405
Reputation: 2166
Yep, there are a few steps we need to take to make your plot. First I remake TiA and CvSS as the proportion, then I melt the df.
require(reshape2)
require(ggplot2
Region <- c("A", "B", "C")
TiA <- c(2065.8408, 1020.1331, 742.8428)
CvSS <- c(1.549020, 1.422771, 1.174165)
TiA.sum<-sum(TiA)
CvSS.sum<-sum(CvSS)
TiA<-TiA/TiA.sum
CvSS<-CvSS/CvSS.sum
df <- data.frame(Region, TiA, CvSS)
require(reshape2)
df.m<-melt(df)
print(df.m)
require(ggplot)
qplot(data=df.m,x=variable,y=value,fill=Region,geom='bar',stat="identity")
The output graph looks like this
edit Spacedman's comment shows a simpler and better way of achieving the same graph.
Upvotes: 1
Reputation: 94182
Its a one-liner starting from your df
object:
require(reshape2)
ggplot(melt(df),
aes(x=variable, y=value, fill=Region)) +
geom_bar(position="fill",stat="identity")
if you want nicer labels:
ggplot(melt(df,variable.name="Code", value.name="Fraction") ,
aes(x=Code, y=Fraction, fill=Region)) +
geom_bar(position="fill",stat="identity")
will give them to you.
Upvotes: 1