You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R的geom_col()绘图中切换柱状图的列顺序

调整柱状图顺序的解决方案

要让Budgeted(预算值)对应柱子排第一、Actual(实际值)对应柱子排第二,核心是指定Type列的渲染顺序,以下是两种直接可行的方法:

方法1:预处理数据时修改因子水平

在加载数据后,重新定义Type的因子水平顺序,让ggplot按指定规则渲染:

library(tidyverse)
library(ggplot2)
library(scales)

Mississppi <- as.data.frame(R_test_8)
# 强制指定Type的水平顺序:Budgeted在前,Actual在后
Mississppi <- Mississppi %>% 
  mutate(Type = factor(Type, levels = c("Budgeted", "Actual")))

# 原绘图代码保留(可删除重复的geom_point())
ggplot() + 
  geom_col(data = Mississppi, aes(x = Ship, y = Mandays, fill = Type), position = "dodge") + 
  geom_point() +
  scale_y_continuous(labels = label_number(suffix = " K", scale = 1e-3), 
                     limits = c(0, 400000), 
                     breaks = seq(0, 400000, by = 50000)) + 
  geom_hline(yintercept = 200000, color = "#7c7d81", linetype = 2) + 
  scale_fill_manual(values = c("#6b9bb1", "#102031")) + 
  theme_classic() + 
  theme(axis.title.x = element_blank(), axis.title.y = element_blank()) + 
  ggtitle("Days of Labor (Thousands)")

方法2:在绘图时通过scale参数指定顺序

如果不想修改原始数据,可直接在scale_fill_manual()中用breaks参数强制指定顺序:

ggplot() + 
  geom_col(data = Mississppi, aes(x = Ship, y = Mandays, fill = Type), position = "dodge") + 
  geom_point() +
  scale_y_continuous(labels = label_number(suffix = " K", scale = 1e-3), 
                     limits = c(0, 400000), 
                     breaks = seq(0, 400000, by = 50000)) + 
  geom_hline(yintercept = 200000, color = "#7c7d81", linetype = 2) + 
  # 通过breaks指定顺序,颜色对应保持不变
  scale_fill_manual(values = c("#6b9bb1", "#102031"), 
                    breaks = c("Budgeted", "Actual")) + 
  theme_classic() + 
  theme(axis.title.x = element_blank(), axis.title.y = element_blank()) + 
  ggtitle("Days of Labor (Thousands)")

注:你的代码里重复了两次geom_point(),可以删除其中一次减少冗余。

内容的提问来源于stack exchange,提问作者tatertot2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 05:12:38