In my heatmap I would like to order Species based on percent value (decreasing) in Haul 1. Here is my current code:
ggplot(data, aes(Haul, Species)) geom_tile(aes(fill = Percent)) scale_fill_gradient(low = "white", high = "red") labs(fill = "% Sites") theme_bw()
So the Species order should be b, c, d, a, based on decreasing Percent in Haul 1. I have tried using reorder() but can't find a way to specify the ordering based on Haul 1.
ggplot(data, aes(Haul, reorder(Species, Percent))) geom_tile(aes(fill = Percent)) scale_fill_gradient(low = "white", high = "red") labs(fill = "% Sites") theme_bw()
My dataframe is set up like this:
Species = rep(c("a","b","c","d"),3)
Haul = rep(c(1,2,3),4)
Percent = c(25,0,25,50,25,0,75,0,50,100,0,50)
data = data.frame(Species, Haul, Percent)
Thank you for your help!
Elise
CodePudding user response:
In the reorder
, we can use ifelse
to make other haul values NA
:
ggplot(data, aes(Haul, reorder(Species, ifelse(Haul == 1, Percent, NA), na.rm = TRUE)))
geom_tile(aes(fill = Percent))
scale_fill_gradient(low = "white", high = "red")
labs(fill = "% Sites", y = "Species")
theme_bw()