Sort Boxplot by Median in R (4 Examples) | Base R & ggplot2 | Reorder Grouped Boxplots & Barcharts

preview_player
Показать описание
R code of this video:

rnorm(25, 1),
rnorm(25, 4),
rnorm(25, 3)),
group = rep(LETTERS[1:4],
each = 25))
head(data) # Print head of example data frame

boxplot(value ~ group, # Draw Base R boxplot with default order
data)

group_ordered <- with(data, # Order boxes by median
reorder(group,
value,
median))
group_ordered # Print order

boxplot(value ~ group_ordered, # Draw Base R boxplot ordered by median
data)

library("ggplot2")

ggplot(data, # Draw ggplot2 boxplot with default order
aes(x = group,
y = value)) +
geom_boxplot()

data_ordered <- data # Create data frame with reordered group levels
data_ordered$group <- factor(data_ordered$group,
levels = levels(group_ordered))

ggplot(data_ordered, # Draw ggplot2 boxplot ordered by median
aes(x = group,
y = value)) +
geom_boxplot()

data_subgroup <- data # Create example data frame with subgroups
data_subgroup$subgroup <- letters[1:5]
head(data_subgroup) # Print head of example data frame

ggplot(data_subgroup, # Draw grouped boxplot with default order
aes(x = group,
y = value,
fill = subgroup)) +
geom_boxplot()

ggplot(data_subgroup, # Draw grouped boxplot ordered by median
aes(x = group,
y = value,
fill = reorder(subgroup,
value,
median))) +
geom_boxplot(data = data_subgroup[data_subgroup$group == "A", ]) +
geom_boxplot(data = data_subgroup[data_subgroup$group == "B", ]) +
geom_boxplot(data = data_subgroup[data_subgroup$group == "C", ]) +
geom_boxplot(data = data_subgroup[data_subgroup$group == "D", ]) +
scale_fill_discrete(name = "subgroup", breaks = sort(unique(data_subgroup$subgroup)))

data_aggr <- aggregate(value ~ group + subgroup, # Calculate mean by subgroup
data_subgroup,
mean)
data_aggr # Print data frame with mean values

ggplot(data_aggr, # Draw grouped barplot with default order
aes(x = group,
y = value,
fill = subgroup)) +
geom_col(position = "dodge")

ggplot(data_aggr, # Draw grouped barplot ordered by mean
aes(x = group,
y = value,
fill = reorder(subgroup,
value))) +
geom_col(data = data_aggr[data_aggr$group == "A", ], position = "dodge") +
geom_col(data = data_aggr[data_aggr$group == "B", ], position = "dodge") +
geom_col(data = data_aggr[data_aggr$group == "C", ], position = "dodge") +
geom_col(data = data_aggr[data_aggr$group == "D", ], position = "dodge") +
scale_fill_discrete(name = "subgroup", breaks = sort(unique(data_aggr$subgroup)))

Follow me on Social Media:

Рекомендации по теме
visit shbcf.ru