R 如何制作已排序的几何图形条()ggplot
我的数据帧称为:R 如何制作已排序的几何图形条()ggplot,r,sorting,ggplot2,geom-bar,R,Sorting,Ggplot2,Geom Bar,我的数据帧称为: d3变量名称:课程名称、id、注册总数、总容量 我做到了: 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,
d3
变量名称:课程名称、id、注册总数、总容量
我做到了:
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
d3a这里是一个重新定义因子
级别顺序的示例
注意,由于您没有提供示例数据,我将模拟一些数据
# 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;
#示例数据
种子集(2017);
为此: