是否可以为ggplot2中的每个条分别放置标签?
在描述性伪代码中,类似
geom_bar(bar 1) +
geom_text(#bar 1) +
geom_bar(bar 2) +
geom_text(#bar 2)
答案 0 :(得分:0)
一种可能的解决方案...
# Grouping 1 has levels G1_A, G1_B
# Grouping 2 has levels G2_A, G2_B
# make plot for G1_A and both {G2_A, G2_B}
# {label here} ============= | ================ {label here}
# {label here} ======= | =========== {label here}
# {label here} === | ====== {label here}
# Init ggplot object
g <- ggplot(data = subset(testdf, grouping_1=="G1_A"), aes(x=Layer, y=Number, fill=grouping_2))
# Layer data for G2_A
g <- g + geom_bar(data = subset(testdf, grouping_2=="G2_A" & grouping_1=="G1_A") , stat = "identity")
# Layer data for G2_B
g <- g + geom_bar(data = subset(testdf, grouping_2=="G2_B" & grouping_1=="G1_A") , stat = "identity")
g <- g + labs(title="G1_A", x =" ", y = "Number (x1000)")
# Axes + ticks
g <- g + scale_y_continuous(breaks = seq(-270000, 80000, 25000),
labels = paste0(as.character(c(seq(270, 0, -25), seq(5, 80, 25))) ) )
# Limits to make sure labels show well
g <- g + expand_limits(y=c(-310000,120000))
# Layer labels for G2_A (move to the left)
g <- g + geom_text(data = subset(testdf, grouping_2=="G2_A" & grouping_1=="G1_A"),
aes(label=Reporting), vjust=+0.5, hjust=1.2, color="black", size=2.5)
# Layer labels for G2_B (move to the right)
g <- g + geom_text(data = subset(testdf, grouping_2=="G2_B" & grouping_1=="G1_A"),
aes(label=Reporting), vjust=+0.5, hjust=-0.3, color="black", size=2.5)
# Common. Add 90deg rotation here
g <- g + scale_fill_brewer(palette = "Set1") +
theme_minimal() + theme(axis.text.x = element_text(angle = 60)) +
coord_flip()