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

如何在R的ggplot中按数字而非字符串排序索引图例?

问题:如何修改ggplot代码让图例按数字顺序排序?

用户提供的ggplot代码如下:

gg = ggplot() +  geom_line(data = correctAnswersPerStimu_1010v1, size=1,
                           aes(x=as.character(testPhase), y=percent_correct, group=as.character(individualIndex), colour = as.character(individualIndex)))


gg = gg + geom_point(data = correctAnswersPerStimu_1010v1, aes(x=as.character(testPhase), y=percent_correct),
                    shape = 23, size = 3, color="black", stroke = 1)

gg = gg + labs(title=paste("Experiment 1010 stimuli correct answers % per phase", sep = ""),
              x ="Phase", y = "% Correct", fill="Phase")

gg = gg + guides(color = guide_legend(title = "Index")) + ylim(0, 100)

gg

当前图表图例按字符串字典序(0,1,10,11…)排序,需求是改为数字顺序(0,1,2,3…14,15)。


解决方案

方法1:将individualIndex转为有序因子(推荐)

问题根源是individualIndex被转为字符型后,按字典序排序。提前将其转为有序因子,指定数字顺序的水平:

在ggplot代码前添加数据处理代码:

# 将individualIndex转为有序因子,水平按0到15的数字顺序排列
correctAnswersPerStimu_1010v1$individualIndex <- factor(
  correctAnswersPerStimu_1010v1$individualIndex,
  levels = as.character(0:15),
  ordered = TRUE
)

然后修改ggplot中aes里的参数,去掉as.character():

# geom_line的aes部分修改为
aes(x=as.character(testPhase), y=percent_correct, group=individualIndex, colour = individualIndex)

这样ggplot会自动按因子的水平顺序渲染图例。

方法2:在scale_color_discrete中指定breaks

如果不想修改原始数据,可以在ggplot代码末尾添加scale_color_discrete,强制指定图例的显示顺序:

gg = gg + scale_color_discrete(breaks = as.character(0:15))

该参数会强制图例按breaks指定的顺序排列,覆盖默认的字符排序。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:55:34