2017-12-14 22 views
-1

をggplot 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 

そして、何私が取得すると、このです:Image

私が何をしても、降順でオレンジバーを並べ替えることはできません。 これを行う方法はありますか?変数total_enrolledをソートしたいと思います。

PS:ひどくフォーマットされたコードをお詫びします、私はまだstackoverflowを考え出しています。

+0

この: https://stackoverflow.com/questions/3253641/change-the-order-of-a-discrete-x-scale – Art

答えて

0

ここでは、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; 

enter image description here

関連する問題