我有以下命令,我想以有序的方式绘制直方图。
所以代码如下:
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)
输出结果为:
我想以有序的方式排列条形码,因此我在reorder()
中使用aes
函数,但这会给我带来以下问题:
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)
答案 0 :(得分:2)
以下是您正在寻找的行为的可重现示例。它是从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")