在geom_bar中重新排序栏

时间:2018-05-25 22:31:47

标签: r ggplot2 geom-bar

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

这是我的代码:

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

它给出: enter image description here

我想切换2厘米杆和2到10厘米杆的位置。因此,从上到下,y轴应为:垃圾,2厘米,2至10厘米,10至20厘米。 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

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)

答案 1 :(得分:0)

使用特定订单的列

创建数据框
# 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)

使用新列

指定特定订单
# Specifying the levels
count_data$horizon <- factor(count_data$horizon, levels =             
count_data$horizon[order(count_data$order)])

绘图

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

<强>输出   https://raw.githubusercontent.com/magoavi/stackoverflow/master/50537609.png

相关问题