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

如何为ggplot图表添加与color参数值不同的自定义标签?

替换ggplot图例标签的两种方法

要把v2x_regime的0(独裁制)、1(民主制)对应的图例标签换成中文,你可以用下面两种简单的实现方式:

方法1:直接在scale_color_manual中指定标签

在原代码的scale_color_manual里添加labels参数,注意标签顺序要和因子水平、颜色值对应(v2x_regime转成因子后默认水平顺序是0、1):

ggplot(output1, aes(Year, SuPDem, color = as.factor(v2x_regime))) +
  geom_line(size = 0.6) +
  scale_color_manual(
    values = c("orange", "blue"),
    labels = c("独裁制", "民主制")  # 第一个标签对应0,第二个对应1
  ) +
  theme_minimal(base_size = 5)

方法2:提前转换为带标签的因子(更推荐)

先把v2x_regime转换成带有中文标签的因子变量,后续绘图直接使用这个新变量,逻辑更清晰也更易维护:

# 生成带标签的因子列
output1$regime_type <- factor(
  output1$v2x_regime,
  levels = c(0, 1),
  labels = c("独裁制", "民主制")
)

# 绘图时直接引用新变量
ggplot(output1, aes(Year, SuPDem, color = regime_type)) +
  geom_line(size = 0.6) +
  scale_color_manual(values = c("orange", "blue")) +
  theme_minimal(base_size = 5)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:35:34