我在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到10厘米杆的位置。因此,从上到下,y轴应为:垃圾,2厘米,2至10厘米,10至20厘米。 有什么想法吗?
答案 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