问题
So I have this data table
AA BB CC DD
W1 3.5 3.5 3.4 3.5
w2 3.4 3.7 3.6 3.5
w3 3.5 3.4 3.5 3.5
w4 3.5 3.4 3.5 3.5
w5 3.5 3.4 3.5 3.5
w6 3.5 3.4 3.5 3.5
w7 3.5 3.4 3.5 3.5
w8 3.5 3.4 3.5 3.5
and code
qw<-barplot(as.matrix(t(tabela.matrix1)), beside=TRUE,
col=c("yellow", "cornflowerblue", "yellowgreen","orchid4"))
text(qw, 0, round(as.matrix(t(tabela.matrix1)), 1),cex=1,pos=3,srt=90)
#legend("bottom",
# c("AA","BB","CC", "DD"),
# fill=terrain.colors(4)
)
that outputs this barplot
Now I would like to plot this barplots, place the legend outside barplot and also rotate leters w1, w2, w3, w4... for 45 degrees.:
Picture above was created in excel.
回答1:
Although the facetting works as well, it is also possible to make the bars smaller. Off course with adjusting the dodging of bars and text:
ggplot(xym, aes(x = Var1, y = value, fill = Var2)) +
theme_bw() +
scale_fill_brewer(palette = "Set1") +
theme(legend.position = "bottom", axis.text.x = element_text(angle = 90,vjust = 0.2)) +
geom_bar(stat = "identity", width = 0.7, position = position_dodge(width=0.7)) +
geom_text(aes(x = Var1, y = 0.05, label = round(value, 2), fill = Var2),
angle = 90, position = position_dodge(width = 0.7), size = 4)
回答2:
This one comes close. I'm not happy with the dodging.
xy <- matrix(runif(4*8), nrow = 8, ncol = 4)
colnames(xy) <- c("AA", "BB", "CC", "DD")
rownames(xy) <- paste("w", 1:nrow(xy), sep = "")
library(ggplot2)
library(reshape2)
xym <- melt(xy)
ggplot(xym, aes(x = Var1, y = value, fill = Var2)) +
theme_bw() +
scale_fill_brewer(palette = "Set1") +
theme(legend.position = "bottom", axis.text.x = element_text(angle = 90,vjust = 0.2)) +
geom_bar(stat = "identity", position = "dodge") +
geom_text(aes(x = Var1, y = 0.05, label = round(value, 2), fill = Var2),
angle = 90, position = position_dodge(width = 1.03), size = 4)
This is a trivial extension of @Roman's solution, putting the Ws into facets.
ggplot(xym, aes(x = Var2, y = value, fill = Var2)) +
theme_bw() +
scale_fill_brewer(palette = "Set1") +
theme(legend.position = "bottom", axis.text.x = element_text(angle = 90,vjust = 0.2)) +
geom_bar(stat = "identity", position = "dodge") +
geom_text(aes(x = Var2, y = 0.1, label = round(value, 2), fill = Var2),
angle = 90, position = position_dodge(width = 1.03), size = 4)+
facet_grid(.~Var1, scales="free_x")
来源:https://stackoverflow.com/questions/32678197/barplot-customization