这是数据集: https://www.dropbox.com/s/mrlfnh6e2ww1xwd/home.csv?dl=0
这是我的代码:
hom <- read.csv(file.choose(),header=TRUE)
home.melt <- melt(hom, id.vars='home')
ggplot(home.melt,
aes(x = reorder(home, value), y = value,
fill=forcats::fct_rev(variable))) +
geom_bar(stat = "identity",width = 0.8) + coord_flip() +
theme_minimal(base_size=10) +
labs(title="Home time",
subtitle="By matches",
x="Home",
y="time (minutes)",
fill=" ")
这是输出:
正如你所看到的那样,它没有以降序排列。
答案 0 :(得分:2)
关键是指定重新排序调用中的函数:
reorder(home, value, FUN = sum)
默认为&#34;表示&#34;
ggplot(home.melt,
aes(x = reorder(home, value, FUN = sum), y = value,
fill=forcats::fct_rev(variable))) +
geom_bar(stat = "identity",width = 0.8) + coord_flip() +
theme_minimal(base_size=10) +
labs(title="Home time",
subtitle="By matches",
x="Home",
y="time (minutes)",
fill=" ")
答案 1 :(得分:1)
library(data.table)
library(ggplot2)
hom <- fread("home.csv")
home.melt <- melt(hom, "home")
home.melt[, variable := factor(variable, levels = sort(unique(variable), decreasing = TRUE))]
ggplot(home.melt, aes(home, value, fill = variable)) +
geom_bar(stat = "identity",width = 0.8) +
coord_flip() +
theme_minimal(base_size = 10) +
scale_x_discrete(limits = home.melt[, sum(value), home][order(V1), home]) +
scale_fill_brewer(palette = "Dark2") +
labs(title = "Home time",
subtitle = "By matches",
x = "Home",
y = "Time (minutes)",
fill = NULL)