R语言堆叠柱状图堆叠顺序修正及图例标题异常问题求助
Hey there! Let's work through those two stacked bar chart issues you're facing—they're totally fixable with a few quick tweaks.
The default descending stack order usually happens because your grouping variable is treated as a factor with levels sorted alphabetically or by value. To lock in a specific, consistent stack order:
First, explicitly set the factor levels of your grouping column to the order you want the stacks to appear (pick whether you want them bottom-to-top or top-to-bottom). For example, if you want groups ordered Low → Medium → High from bottom to top:
# Adjust your data frame's grouping factor levels df$group <- factor(df$group, levels = c("Low", "Medium", "High"))
Then, when you build your plot (using ggplot2, the most common tool for this in R), the stack will follow the factor level order automatically:
library(ggplot2) ggplot(df, aes(x = category, y = value, fill = group)) + geom_col() # geom_col uses position_stack() by default, which follows factor levels
If you ever need to reverse the stack order later, just add position = position_stack(reverse = TRUE) inside geom_col().
factor(title,levels...) Legend Title That weird legend title pops up because your fill variable is a factor, and ggplot is pulling the underlying factor metadata as the title. To get rid of it entirely, use either labs() or guides() to set the fill legend title to NULL:
Option 1 (cleanest for most cases):
ggplot(df, aes(x = category, y = value, fill = group)) + geom_col() + labs(fill = NULL) # This blanks out the legend title
Option 2 (great if you need extra control over other legend settings):
ggplot(df, aes(x = category, y = value, fill = group)) + geom_col() + guides(fill = guide_legend(title = NULL))
Either of these will strip that annoying factor(title,levels...) text from your legend.
内容的提问来源于stack exchange,提问作者Yrden

