These are the code and example data for obtaining a stacked barplot with ggplot. Please paste the following example in a text file called "data":
Var1 Var2 value
a z 0.17835287
b z 0.20872632
c z 0.54772440
d z 0.04270081
e z 0.02249560
and then run in R:
if (!require("ggplot2")) {
install.packages("ggplot2", repos="http://cran.rstudio.com/")
library("ggplot2")
}
library("ggplot2")
data = read.delim("data", sep = " ")
ggplot(data[!is.na(data$value),], aes(x = Var2, y = value, fill = factor(Var1))) +
geom_bar(stat = "identity") +
scale_fill_manual(values=c("#FFED00", "#ffffff", "#ffffff", "#00008F", "#ffffff")) +
scale_fill_manual(values=c("#5AFFA5", "#800000", "#DB0000", "#BE1FC1", "#0047FF")) +
facet_grid(Var1~., as.table=FALSE, scale="free_y", space = "free_y") +
theme_minimal() +
geom_vline(xintercept=length(levels(data$Var2)) + 0.5, size=0.3) +
scale_y_continuous(breaks=seq(0, 1, 0.05), expand = c(0, 0)) +
theme(legend.position="none",
axis.text.x = element_text(angle = 45, colour="black", vjust = 1, size=8, hjust=1),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_text(size=4),
axis.ticks.y = element_line(size = 0.3, colour = "black", linetype = "solid"),
axis.line.y=element_line(),
strip.text.y=element_text(size = 8, colour="black", family="",angle=00, hjust = 0),
panel.grid=element_blank(),
axis.line=element_line(size = 0.3, colour = "black", linetype = "solid"),
axis.ticks.x=element_line(size = 0.3, colour = "black", linetype = "solid"),
panel.background=element_blank(), panel.margin = unit(0, "lines"),
plot.margin = unit(c(0.4,0,0.2,0.4), "cm"))
You should then see a plot like this one:
Now I would like to make that some of the stacked bars (a and d) be composed by a background color and another color superimposed on the former, in the shape of stripes, something like the "density" option in the "barplot" function:
barplot(c(1), col=c("red"))
barplot(c(1), density=c(2), col=c("blue"), add=T)
To do so, what I was trying was to run twice the "scale_fill_manual" option of ggplot, the first one just filling with colors the a and d bars:
and then the second one filling all the bars but changing the color of the a and d bars. The problem is that ggplot just overrides the first "scale_fill_manual", and what I would like to do is that the second time the colors of the a and d bars and printed superimposed on the previous, in the shape of stripes. Summing up, the result would be roughly something like this (superimposing the 3rd plot over the 1 plot):
Do you know any tweak I can do in the "scale_fill_manual" option in order to force this?
Thanks