-1

My dataframe is called:

d3with variable names : course_name,id,total_enrolled,total_capacity

I did:

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

And what I get is this: Image

No matter what I do I can't sort the orange bar in descending order. Is there a way to do that? I would like to sort on the variable total_enrolled.

PS:I apologize for the badly formatted code,I am still figuring out stackoverflow.

Sraw
  • 18,892
  • 11
  • 54
  • 87
Iniciador
  • 93
  • 2
  • 8
  • This: https://stackoverflow.com/questions/3253641/change-the-order-of-a-discrete-x-scale – Art Dec 14 '17 at 03:35

1 Answers1

0

Here is a an example redefining the order of the factor levels.

Note, since you don't provide sample data I will simulate some data.

# 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;

enter image description here

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68