我在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')它提供了:

我想把2厘米棒和2厘米棒的位置换一下。因此,从上到下,y轴应该是:垃圾,2厘米,2到10厘米,10到20厘米。有什么想法吗?
发布于 2018-05-26 07:10:06
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)发布于 2018-05-26 09:37:57
创建包含特定顺序的列的数据框
# 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')Output https://raw.githubusercontent.com/magoavi/stackoverflow/master/50537609.png
https://stackoverflow.com/questions/50537609
复制相似问题