I have searched around and found cases similar to mine, but I cannot find a working solution to the following.
I have a dataframe like this one:
df <- data.frame(name = rep(c("a","b","c"), each=2), measure_type = rep(c("n1","n2"),3), value=c(20,1,3,3,17,9))
> df
name measure_type value
1 a n1 20
2 a n2 1
3 b n1 3
4 b n2 3
5 c n1 17
6 c n2 9
I want to create a dodged bar plot with ggplot. X-axis should be name, y-axis should be value, fill=measure_type
and the dodged bars sorted according the highest value for measure_type=n1.
The last feature (bold font) is what I am struggling with. I simply do not know how to produce it.
My code so far:
plot <- ggplot(df, aes(x = name, y = value, fill = measure_type)) + geom_bar(stat = "identity", position=position_dodge())
Produces:
I want the smallest value of n1 determine the order of the dodged bar plots.
Thanks for your help.
You can sort by
value
and then set the order ofname
to the sorted order ofname
formeasure_type=="n1"
. This can all be done on the fly using thedplyr
pipe: