Reputation: 515
Here is the dataset: https://www.dropbox.com/s/mrlfnh6e2ww1xwd/home.csv?dl=0
Here is my code:
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=" ")
Here is the output:
As you can see it's not ordered in descending manner.
Upvotes: 3
Views: 2321
Reputation: 28379
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)
Upvotes: 1
Reputation: 19756
The key is specifying the function in the call to reorder:
reorder(home, value, FUN = sum)
the default is "mean"
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=" ")
Upvotes: 7