你可以使用以下语法来改变 ggplot2 图例中项目的顺序:

scale_fill_discrete(breaks=c('item4', 'item2', 'item1', 'item3', ...)

下面的例子展示了如何在实践中使用这种语法。

例子:改变ggplot2图例中项目的顺序

假设我们在ggplot2中创建了下面这个图,在一个图中显示多个boxplots。

library(ggplot2)
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))
#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes(x=team, y=points, fill=team)) +
  geom_boxplot()

为了改变图例中项目的顺序,我们可以使用**scale_fill_discrete()**函数,如下所示。

library(ggplot2)
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))
#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes(x=team, y=points, fill=team)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A'))

注意,项目的顺序从:A、B、C变为B、C、A。

我们还可以使用标签参数来改变图例中项目所使用的具体标签。

library(ggplot2)
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C'),
                 points=c(6, 8, 13, 16, 10, 14, 19, 22, 14, 18, 24, 26))
#create multiple boxplots to visualize points scored by team
ggplot(data=df, aes(x=team, y=points, fill=team)) +
  geom_boxplot() +
  scale_fill_discrete(breaks=c('B', 'C', 'A'),
                      labels=c('B Team', 'C Team', 'A Team'))

注意,图例的标签已经改变。

下面的教程解释了如何在ggplot2中执行其他常见操作:

如何删除ggplot2中的图例
如何改变ggplot2中的图例位置