ggplot堆叠柱状图顺序
时间: 2023-06-29 18:09:57 浏览: 336
在ggplot中,堆叠柱状图的顺序可以使用`reorder()`函数进行排序。假设我们有一个数据集`df`,其中有两个变量`category`和`value`,我们想要按照`value`对`category`进行排序并绘制堆叠柱状图,可以按照以下步骤操作:
1. 使用`reorder()`函数对`category`进行排序,例如:`df$category <- reorder(df$category, df$value)`
2. 使用`ggplot()`函数创建一个空白的绘图对象
3. 使用`geom_col()`函数添加堆叠柱状图,其中`fill`参数指定颜色填充,`position`参数指定堆叠方式,例如:`geom_col(aes(x = category, y = value, fill = category), position = "stack")`
4. 可以使用`scale_fill_manual()`函数自定义颜色顺序,例如:`scale_fill_manual(values=c("red", "green", "blue"))`
完整代码示例:
```
library(ggplot2)
# 创建示例数据
df <- data.frame(category = c("A", "B", "C"), value = c(30, 50, 20))
# 对category按value进行排序
df$category <- reorder(df$category, df$value)
# 绘制堆叠柱状图
ggplot(df, aes(x = category, y = value, fill = category)) +
geom_col(position = "stack") +
scale_fill_manual(values=c("red", "green", "blue"))
```
这样就可以按照`value`的大小对`category`进行排序并绘制堆叠柱状图了。
阅读全文
相关推荐

















