本文介绍了如何在多面ggplot2条形图中订购条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 如果我想从ggplot2条形图中排列条从最大到最小,那么我通常会更新条类别的因子级别,例如 one_group< - data.frame( height = runif(5), category = gl(5,1)) o one_group $ category p_one_group < - ggplot(one_group,aes(category,height))+ geom_bar(stat =identity) p_one_group 如果我有不同的方面有几组不同的barcharts,每个方面都有从最大到最小(以及不同的x轴)排列的条,那么这种技术就会失效。给出一些示例数据 two_groups< - data.frame ( height = runif(10), category = gl(5,2), group = gl(2,1,10,labels = letters [1:2])) 和绘图代码 p_two_groups geom_bar(stat =identity)+ facet_grid(。 〜group,scales =free_x) p_two_groups 我需要做些什么如果有帮助,解决的一个同等问题是:在完成分面之后,我如何更新因子水平? 解决方案这里是一个黑客: two_groups< - transform(two_groups,category2 = factor(paste(group,category))) two_groups< - transform(two_groups,category2 = reorder(category2,rank(height))) ggplot(two_groups,aes(category2,height))+ geom_bar(stat =identity)+ facet_grid(。〜group,scales =free_x)+ scale_x_discrete( labels = two_groups $ category,breaks = two_groups $ category2) make UNIQUE 因子变量用于所有条目(category2) 根据变量重新排列基于高度变量的变量 (x = category2) 重新标记轴使用scale_x_discrete中变量(category2)的原始值(类别)。 If I want to order the bars in a ggplot2 barchart from largest to smallest, then I'd usually update the factor levels of the bar category, like soone_group <- data.frame( height = runif(5), category = gl(5, 1))o <- order(one_group$height, decreasing = TRUE)one_group$category <- factor(one_group$category, levels = one_group$category[o])p_one_group <- ggplot(one_group, aes(category, height)) + geom_bar(stat = "identity")p_one_groupIf have have several groups of barcharts that I'd like in different facets, with each facet having bars ordered from largest to smallest (and different x-axes) then the technique breaks down.Given some sample datatwo_groups <- data.frame( height = runif(10), category = gl(5, 2), group = gl(2, 1, 10, labels = letters[1:2]))and the plotting codep_two_groups <- ggplot(two_groups, aes(category, height)) + geom_bar(stat = "identity") + facet_grid(. ~ group, scales = "free_x")p_two_groupswhat do I need to do to get the bar ordering right?If it helps, an equivalent problem to solve is: how do I update factor levels after I've done the faceting? 解决方案 here is a hack:two_groups <- transform(two_groups, category2 = factor(paste(group, category)))two_groups <- transform(two_groups, category2 = reorder(category2, rank(height)))ggplot(two_groups, aes(category2, height)) + geom_bar(stat = "identity") + facet_grid(. ~ group, scales = "free_x") + scale_x_discrete(labels=two_groups$category, breaks=two_groups$category2)make UNIQUE factor variable for all entries (category2)reorder the variable based on the heightplot on the variable: aes(x=category2)re-label the axis using original value (category) for the variable (category2) in scale_x_discrete. 这篇关于如何在多面ggplot2条形图中订购条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-19 04:08