简体   繁体   English

重新排列geom_bar中的栏

[英]Reorder bars in geom_bar

I have a bar plot that I made using ggplot2 in R. I want to move some of the bars around. 我在R中使用ggplot2制作了一个条形图。我想移动一些条形图。 I've seen a few explanations for how to reorder by percentage, but I want to sort mine into a particular order that is determined by the name of the variables. 我已经看到了一些有关如何按百分比重新排序的解释,但是我想将我的排序到由变量名称确定的特定顺序中。

Here is my code: 这是我的代码:

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

It gives: 它给: 在此处输入图片说明

I would like to switch the positions of the 2 cm bar and the 2 to 10 cm bar. 我想切换2 cm栏和2到10 cm栏的位置。 So, from top to bottom, the y-axis should read: Litter, 2 cm, 2 to 10 cm, 10 to 20 cm. 因此,y轴从上到下应为:垃圾,2厘米,2至10厘米,10至20厘米。 Any ideas? 有任何想法吗?

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)

Creating data frame with a column for the specific order 使用特定顺序的列创建数据框

# 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 specific order using the new column 使用新列指定特定顺序

# Specifying the levels
count_data$horizon <- factor(count_data$horizon, levels =             
count_data$horizon[order(count_data$order)])

Plotting 绘图

# 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 输出 https://raw.githubusercontent.com/magoavi/stackoverflow/master/50537609.png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM