如何制作排序的 geom_bar() ggplot

How to make a sorted geom_bar() ggplot

我的数据框名为:

d3变量名:course_name,id,total_enrolled,total_capacity

我做到了:

d3a <- head(d3[order(d3$total_capacity, decreasing = T),], 15)
d3.plottable <- d3a[, c(1,3,4)]
d3.plottable <- melt(d3.plottable, id.vars = "course_name")

library(ggplot2)

g <- ggplot(d3.plottable, aes(x = course_name, y = value))
g + geom_bar(aes(fill = variable), position = position_dodge(), stat = "identity") + 
  coord_flip() + theme(legend.position = "top")
g <- g + labs(x = "Course Name")
g <- g+ labs(y = "Number of Students")
g

我得到的是:

无论我做什么,我都无法按降序对橙色条进行排序。 有没有办法做到这一点?我想对变量 total_enrolled.

进行排序

PS:对于格式错误的代码,我深表歉意,我仍在研究计算器。

这是一个重新定义 factor 级别顺序的示例。

注意,由于您没有提供样本数据,我将模拟一些数据。

# Sample data
set.seed(2017);
df <- cbind.data.frame(
    course_name = rep(LETTERS[1:6], each = 2),
    value = sample(300, 12),
    variable = rep(c("total_enrolled", "total_capacity"), length.out = 12)
);

# Relevel factor levels, ordered by subset(df, variable == "total_enrolled")$value
df$course_name <- factor(
    df$course_name,
    levels = as.character(subset(df, variable == "total_enrolled")$course_name[order(subset(df, variable == "total_enrolled")$value)]));

# Plot
require(ggplot2);
g <- ggplot(df, aes(x = course_name, y = value))
g <- g + geom_bar(aes(fill = variable), position = position_dodge(), stat = "identity");
g <- g + coord_flip() + theme(legend.position = "top");
g <- g + labs(x = "Course Name")
g <- g + labs(y = "Number of Students")
g;