我有一个虚拟数据集:
tmp <- structure(list(order = c("John", "John", "John", "Ross", "Ross",
"Ross", "John", "John", "John", "Ross", "Ross", "Ross"), value = c(39,
40, 13, 19, 13, 15, -12, -3, 0, -4, -1, 0), Category = c("VU",
"EN", "CR", "VU", "EN", "CR", "VU", "EN", "CR", "VU", "EN", "CR"
), perc = c(NA, NA, NA, NA, NA, NA, NA, "14%", NA, NA, "9.6%",
NA)), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 25L, 26L, 27L, 28L,
29L, 30L), class = "data.frame")
我想在每个条形图的顶部显示图表左侧的百分比(负值)。这是我的代码:
ggplot(tmp,
aes(fill = Category, y = value, x = reorder(order, value))) +
# add light grey vertical lines in correspondance of x axis thicks
geom_hline(yintercept = c(seq(-20, 0, 5), seq(0, 100, 20)), colour = "grey92") +
# add stacked bars with grey contouring
geom_bar(position = "stack", stat = "identity", alpha = .8, color = "grey50") +
# add zero vertical line
geom_hline(yintercept = 0, colour = "grey50", linewidth = 1.5, linetype = "dashed") +
# add % for negative values
geom_text(aes(label = perc),
hjust = 2,
size = 10) +
# add y axis breaks and limits
scale_y_continuous(breaks = c(seq(-20, 0, 10), seq(0, 100, 20)),
limits = c(-36, 100),
expand = c(0, 0)) +
# add discrete colour scale
scale_fill_manual(values = c("#E55C30FF","#FBB91FFF","#FCFFA4FF")) +
# flip horizontally
coord_flip()
由于有些条形比其他条形长,如果我尝试一下hjust
,我可以同时移动所有标签。有没有办法让所有标签显示在条形的顶部(在本例中,在侧面,因为它是水平条形图)?
position=position_stack()
您也可以通过使用标签来实现所需的结果,设置vjust=0
将标签放置在条形图内,最后使用hjust = 1
。另请注意,我切换到,geom_label
因为它允许在标签周围添加一些填充,但这需要设置fill=NA
和label.size=0
摆脱标签周围的框。此外,我们必须在group
aes 上进行映射。