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

如何在ggplot2中调整条形图图例顺序(交换Close与Far)

解决方法

要交换图例中Close和Far的位置并保持Inside在底部,有两种简单的实现方式:

方法一:将变量z转为有序因子

直接在数据层面定义z的顺序,后续所有可视化都会遵循这个规则:

y <- c(1,1,1,1,1)
x <- c("Bolt", "Zipp", "Voi", "Bolt", "Zipp")
z <- c("Inside", "Inside", "Close", "Far", "Far")
# 把z转换成因子,指定levels顺序为Far→Close→Inside,确保Inside在图例底部
df <- data.frame(x, y, z = factor(z, levels = c("Far", "Close", "Inside")))

df %>%
  ggplot(aes(x = x,
             y = y,
             fill = z)) +
  labs(x = "Operator",
       y = "Amount of vehicles",
       fill = "Proximity") +
  geom_bar(stat = "identity") +
  scale_fill_grey() +
  theme_bw()

方法二:在颜色比例尺中指定图例顺序

如果不想修改原始数据,可直接在scale_fill_grey()里通过breaks参数调整图例显示顺序:

y <- c(1,1,1,1,1)
x <- c("Bolt", "Zipp", "Voi", "Bolt", "Zipp")
z <- c("Inside", "Inside", "Close", "Far", "Far")
df <- data.frame(x, y, z)

df %>%
  ggplot(aes(x = x,
             y = y,
             fill = z)) +
  labs(x = "Operator",
       y = "Amount of vehicles",
       fill = "Proximity") +
  geom_bar(stat = "identity") +
  scale_fill_grey(breaks = c("Far", "Close", "Inside")) + # 自定义图例顺序
  theme_bw()

两种方法都能实现需求:Inside留在图例底部,Close和Far的位置互换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:40:41