首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在geom_bar中重新排序条形图

在geom_bar中重新排序条形图
EN

Stack Overflow用户
提问于 2018-05-26 06:31:47
回答 2查看 1.4K关注 0票数 0

我在R中使用ggplot2制作了一个条形图,我想移动一些条形图。我已经看到了一些关于如何按百分比重新排序的解释,但我想将我的解释排序为由变量名称确定的特定顺序。

下面是我的代码:

代码语言:javascript
复制
# make OTU count data frame
count=c(Count_Litter, Count_02, Count_0210, Count_1020)
horizon=c('Litter', '2 cm', '2-10 cm', '10-20 cm')
count_data=data.frame(horizon, count)

# make bar chart
plot=ggplot(data=count_data, aes(x=horizon, y=count))
final_plot=plot + geom_bar(position='dodge', stat= 'identity', fill= 
    'red') + coord_flip() + geom_text(aes(label=count), hjust=1) + 
    labs(title='Number of OTUs by Horizon')

它提供了:

我想把2厘米棒和2厘米棒的位置换一下。因此,从上到下,y轴应该是:垃圾,2厘米,2到10厘米,10到20厘米。有什么想法吗?

EN

回答 2

Stack Overflow用户

发布于 2018-05-26 07:10:06

代码语言:javascript
复制
count <- 1:4
#Change your horizon to a ordered factor and it should be fine.
horizon=factor(c('Litter', '2 cm', '2-10 cm', '10-20 cm'),
                   levels = c('Litter', '2 cm', '2-10 cm', '10-20 cm'),
                   ordered = T)
票数 0
EN

Stack Overflow用户

发布于 2018-05-26 09:37:57

创建包含特定顺序的列的数据框

代码语言:javascript
复制
# Library
library(ggplot2)

# Re-creating the data frame
count=c(556527, 132732, 129880, 148088)
horizon=c('Litter', '2 cm', '2-10 cm', '10-20 cm')
# Specifying the order in which the bar should appear
order=c(4, 3, 2, 1)
count_data=data.frame(horizon, count, order)

使用新列指定特定顺序

代码语言:javascript
复制
# Specifying the levels
count_data$horizon <- factor(count_data$horizon, levels =             
count_data$horizon[order(count_data$order)])

绘图

代码语言:javascript
复制
# making horizontal bar chart
plot=ggplot(data=count_data, aes(x=horizon, y=count))
plot + 
  geom_bar(position='dodge', stat= 'identity', fill= 'red') + 
  coord_flip() + 
  geom_text(aes(label=count), hjust=1) + 
  labs(title='Number of OTUs by Horizon')

Output https://raw.githubusercontent.com/magoavi/stackoverflow/master/50537609.png

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50537609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档