更改离散x刻度的顺序

lok*_*art 128 r ggplot2 r-faq

我正在使用具有离散x刻度的ggplot制作一个躲闪条形图,x轴现在按字母顺序排列,但我需要重新排列它以便按y轴的值排序(即,最高的条形将位于左侧).

我尝试了排序或排序,但结果是对x轴进行排序,而不是分别对条形进行排序.

我做错了什么?

Yur*_*kiy 190

对我来说最好的方法是使用带有类别的向量,我需要作为limits参数scale_x_discrete.我认为这是非常简单和直接的解决方案.

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() + 
  scale_x_discrete(limits=c(8,4,6))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我认为这是最好的答案。它控制x轴值的顺序,并且不会变换或影响数据框。尽管在ggplot()调用中,使用factor和reorder会改变数据的特性,因此,处理手头的问题超出了其需要。 (5认同)
  • 这应该是公认的答案!为什么通过编写2到3行代码来使事情复杂化,而您却可以在一条优雅的(预定义)代码行中完成某件事? (2认同)

Ric*_*ton 101

尝试在x轴上手动设置因子的级别.例如:

library(ggplot2)
# Automatic levels
ggplot(mtcars, aes(factor(cyl))) + geom_bar()    
Run Code Online (Sandbox Code Playgroud)

自动确定因子水平的汽车数据集的ggplot

# Manual levels
cyl_table <- table(mtcars$cyl)
cyl_levels <- names(cyl_table)[order(cyl_table)]
mtcars$cyl2 <- factor(mtcars$cyl, levels = cyl_levels)
# Just to be clear, the above line is no different than:
# mtcars$cyl2 <- factor(mtcars$cyl, levels = c("6","4","8"))
# You can manually set the levels in whatever order you please. 
ggplot(mtcars, aes(cyl2)) + geom_bar()
Run Code Online (Sandbox Code Playgroud)

具有因子水平的汽车数据集的ggplot手动重新排序

正如詹姆斯在他的回答中指出的那样,reorder是重新排序因子水平的惯用方式.

mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x)))
ggplot(mtcars, aes(cyl3)) + geom_bar()
Run Code Online (Sandbox Code Playgroud)

使用重新排序功能重新排序因子级别的汽车数据集的ggplot


Jam*_*mes 38

你可以使用reorder:

qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")
Run Code Online (Sandbox Code Playgroud)

编辑:

要拥有左边最高的酒吧,你必须使用一点点kludge:

qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
   data=mtcars,geom="bar")
Run Code Online (Sandbox Code Playgroud)

我希望这也有负面的高度,但事实并非如此,所以它有效!

  • 我很震惊这个答案没有更多的赞成,90%的时候这是正确的方法. (5认同)

jaz*_*rro 26

哈德利一直在开发一个名为的包forcats.这个包使这项任务变得更加容易.fct_infreq()当您想要通过因子的频率更改x轴的顺序时,可以利用.对于本文中的mtcars示例,您希望cyl按每个级别的频率重新排序级别.最常出现的级别保留在左侧.你所需要的只是fct_infreq().

library(ggplot2)
library(forcats)

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")
Run Code Online (Sandbox Code Playgroud)

如果你想反过来,你可以fct_rev()一起使用fct_infreq().

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl") 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述