Reputation: 31
I have been fiddling with a stacked bar chart, which I cannot get to sort from tallest to shortest. Here is the chart I have currently.
The code I am using is below:
ggplot(df7, aes(
x = reorder(cause, failures) ,
y = failures,
fill = factor(
part_number,
levels = c(
"UNKNOWN",
"3766453",
"20R7920",
"3966006",
"3976397",
"20R7916",
"20R7915"
)
)
)) +
geom_bar(
position = "stack",
stat = "identity",
width = 0.7,
alpha = 0.75,
color = 'black'
) +
theme_minimal() +
xlab('') +
ylab('Failures') +
labs(fill = "Part Number") +
scale_fill_brewer(palette = "Dark2") +
coord_flip()
Does anyone see why the chart is not sorting correctly? Thank you, and cheers!
Upvotes: 2
Views: 93
Reputation: 31
reorder
is a generic function for reordering factors. By default it reorders by mean. By default reorder
uses a 'mean' function (FUN = mean
by default) to reorder factors. By setting the FUN argument to sum
reorder will sort the stacked columns by the sum total of the components to each bar.
The reorder section of the code should be replaced with the following:
reorder(cause, failures, FUN=sum)
Upvotes: 1