我正在使用具有离散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)

Ric*_*ton 101
尝试在x轴上手动设置因子的级别.例如:
library(ggplot2)
# Automatic levels
ggplot(mtcars, aes(factor(cyl))) + geom_bar()
Run Code Online (Sandbox Code Playgroud)

# 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)

正如詹姆斯在他的回答中指出的那样,reorder是重新排序因子水平的惯用方式.
mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x)))
ggplot(mtcars, aes(cyl3)) + geom_bar()
Run Code Online (Sandbox Code Playgroud)

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)
我希望这也有负面的高度,但事实并非如此,所以它有效!
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)
| 归档时间: |
|
| 查看次数: |
226357 次 |
| 最近记录: |