【发布时间】:2018-11-29 17:15:19
【问题描述】:
堆叠条形图上的标签没有出现在正确的条形上方;相反,它们的位置对应于相反的条形顺序。
示例数据集:
library(scales)
library(ggplot2)
types <- c('Mostly Satisfied','Somewhat satisfied','Unsatisfied')
df_summ <- data.frame(cust_type = factor(types, levels=types),
cust_count = c(1.2e3, 2.3e3, 3.4e3)
)
df_summ$percent_of_file <- df_summ$cust_count/sum(df_summ$cust_count)
df_summ$label_txt <- paste0(df_summ$cust_type,': ',comma(df_summ$cust_count),' (',
percent(df_summ$percent_of_file),')')
# I need a dummy value for the x axis
df_summ$group <- 'All customers'
我的情节代码:
ggplot(df_summ,
aes(x=group, y = cust_count, label=label_txt))+
geom_bar(aes(fill=cust_type),position='stack',stat='identity')+
geom_text(size = 4,
position = position_stack(vjust = 0.5,
reverse=TRUE) # changing to reverse=FALSE doesn't help
)+
scale_fill_manual(values = setNames(c('green','beige','salmon'), types),
guide=FALSE
) +
labs( x = NULL,
y = NULL,
title = 'Composition of customer base') +
theme_minimal() +
theme ( panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)
如何在保持条形顺序的同时固定标签的位置?
我的问题有点像this question,但带有条形图,解决方案(使用position_stack())在这里对我没有帮助。
【问题讨论】:
-
您在调用
scale_fill_manual时使用character类型,但在实际数据中使用factor(types)。也许您应该最初将它们转换为factor而不仅仅是数据? -
问题是你没有给文本层任何变量来“堆叠”,因为你把
fill美学放在geom_bar()中。您可以将其移至全局aes()(即在ggplot()中)或将aes(group = cust_type)之类的内容添加到geom_text()中。您不需要反转堆叠。 -
@r2evans 感谢您的建议。我最初尝试转换它们,但没有任何区别。
-
@aosmith 这很有意义。谢谢。