通过对数据的一个子集进行排序来重新排序x轴变量 [英] reorder x-axis variables by sorting a subset of the data

查看:115
本文介绍了通过对数据的一个子集进行排序来重新排序x轴变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作堆积条形图,我想根据单个类别的数据重新排列x轴上的变量。在下面的例子中,有三个x值,每个值都对应三个类别。在排列名称值以增加bb丰度时,如何绘制图表成为可能。

I am trying to make a stacked bar chart and I would like to reorder the variables on the x-axis based on the data from a single category. In the example below there are three x values each of which have values corresponding to three categories. How would it be possible to plot the graph while sorting the name values for increasing abundance of "bb".

虽然这个问题与其他有关重新排序 分类 变量这里的区别在于排序基于一列数据的子集。

Although this question is similar to other questions about reordering categorical variables the difference here is that the ordering is based on a subset of one column's data. Any suggestions appreciated.

#create the dataframe
name = c('a', 'a', 'a', 'b', 'b', 'b','c','c','c') 
cat = c("aa", "bb", "cc", "aa", "bb", "cc","aa", "bb", "cc") 
percent = c( 5 , 5, 90, 40, 40 , 20, 90,5,5) 
df = data.frame(name, cat, percent)

#stacked barchart with default ordering   
ggplot(df, aes(x=name,y=percent, fill=cat)) + geom_bar(position="fill")

#I'm looking to reorder the x-axis by the `percent` values for category "bb"
vals = df[ df$cat == 'bb', ]                     #subset
xvals = vals[with(vals, order(percent)), ]$name  #get values
ggplot(df, aes(x =reorder(name, xvals ), y = percent, fill=cat])) + geom_bar(position="fill") #order with new values


推荐答案

df$name2 <- factor(df$name, levels = xvals)
ggplot(df, aes(x = name2, y = percent, fill = cat)) +
  geom_bar(stat = "identity", position = "fill")

这篇关于通过对数据的一个子集进行排序来重新排序x轴变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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