按频率/值订购离散 x 比例 [英] Order discrete x scale by frequency/value

查看:25
本文介绍了按频率/值订购离散 x 比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a dodged bar chart using ggplot with discrete x scale, the x axis are now arranged in alphabetical order, but I need to rearrange it so that it is ordered by the value of the y-axis (i.e., the tallest bar will be positioned on the left).

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

I tried order or sort, but result in sort the x-axis, but not the bars respectively.

我做错了什么?

推荐答案

尝试手动设置 x 轴上的因子水平.例如:

Try manually setting the levels of the factor on the x-axis. For example:

library(ggplot2)
# Automatic levels
ggplot(mtcars, aes(factor(cyl))) + geom_bar()    

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

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

As James pointed out in his answer, reorder is the idiomatic way of reordering factor levels.

mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x)))
ggplot(mtcars, aes(cyl3)) + geom_bar()

这篇关于按频率/值订购离散 x 比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆