R - 重新排序直方图条 - ggplot2

R - reordering histogram bars - ggplot2

我有以下命令,我想按顺序绘制直方图。

所以代码如下:

ggplot(upstream, aes(x=type, y=round(..count../sum(..count..) * 100, 2))) + geom_histogram(fill= "red", color = "red") + xlab ("Vehicle Type") +
    ylab("Percentage of Vehicles in the Category (%)") + ggtitle ("Percentage of Upstream Vehicles by Type") +
    stat_bin(geom="text", aes(label=round(..count../sum(..count..) * 100, 2)), vjust=-0.5)

输出为:

我想按顺序排列条形,所以我在 aes 中使用 reorder() 函数,但这给了我以下问题:

 stat_bin requires the following missing aesthetics x

如何在不出现此错误的情况下使用重新排序?我似乎无法通过发布的解决方案来解决这个问题。

提前感谢您的建议。

编辑 1:我根据 joran 的建议用 geom_bar() 修复了我正在寻找的内容,以防万一有人需要它:

# Reorder the factor you are trying to plot on the x-side (descending manner)
upstream$type <- with(upstream, reorder(type, type, function(x) -length(x)))
# Plotting
ggplot(upstream, aes(x=type, y=round(..count../sum(..count..) * 100, 2))) + geom_bar(fill= "blue", color = "blue") + xlab ("Vehicle Type") +
    ylab("Percentage of Vehicles in the Category (%)") + ggtitle ("Percentage of Upstream Vehicles by Type") +
    stat_bin(geom="text", aes(label=round(..count../sum(..count..) * 100, 2)), vjust=-0.5)

这是您正在寻找的行为的可重现示例。复制自 FAQ: How to order the (factor) variables in ggplot2

# sample data.
d <- data.frame(Team1=c("Cowboys", "Giants", "Eagles", "Redskins"), Win=c(20, 13, 9, 12))

# basic layer and options
p <- ggplot(d, aes(y=Win))

# default plot (left panel)
# the variables are alphabetically reordered.
p + geom_bar(aes(x=Team1), stat="identity")

# re-order the levels in the order of appearance in the data.frame
d$Team2 <- factor(d$Team1, as.character(d$Team1))
# plot on the re-ordered variables (Team2) 
p + geom_bar(aes(x=Team2), data=d, stat="identity")