I'm trying to plot a stacked bar graph in R using ggplot. I also want to include percentage in each piece of bars for that piece. I tried to follow the posts 1, 2, 3 but the values are not exactly in their respective blocks. My data is a file in dropbox.
My code is as follows:
f<-read.table("Input.txt", sep="\t", header=TRUE)
ggplot(data=f, aes(x=Form, y=Percentage, fill=Position)) +
geom_bar(stat="identity", colour="black") +
geom_text(position="stack", aes(x=Form, y=Percentage, ymax=Percentage, label=Percentage, hjust=0.5)) +
facet_grid(Sample_name ~ Sample_type, scales="free", space="free") +
opts(title = "Input_profile",
axis.text.x = theme_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = theme_text(face="bold", size=11),
axis.title.x = theme_text(face="bold", size=9),
axis.title.y = theme_text(face="bold", size=9, angle=90),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank()) +
scale_fill_hue(c=45, l=80)
ggsave("Output.pdf")
The output is-

Any help is greatly appreciated. Thank you for your help and time!



geom_text. It is the height of each bar segment. You need to do some arithmetic to calculate the midpoint (or top, or whatever) of each bar segment, add that as a separate variable and use it as the y variable ingeom_text. The functioncumsummay be helpful.f <- ddply(f, .(Form, Sample_name, Sample_type), transform, pos = (cumsum(Percentage) - 0.5 * Percentage))(requires plyr), then thegeom_textstatement should be:geom_text(aes(x=Form, y=pos, label=Percentage))