I'm trying to reorder the bars on my bargraph so they are biggest to smallest, ordered by log(Max_N) rather than alphabetically. I've tried using forcats but it brings up an error message. This is my code so far, whats going wrong? I'm trying to teach myself how to use ggplot, so please do point out any errors I've made, because I am self-taught!
library("ggplot2")
library (forcats)
test<-ggplot(all, aes(x=all$Species, y=log(all$Max_N 1)))
geom_bar(stat = "identity")
coord_flip()
test <- test labs(title = "",
subtitle = "",
caption = "",
y = "Log(MaxN)", x = "Species",
tag = "")
test %>%
mutate(name = fct_reorder(Species, log(Max_N 1)) %>%
a) Here's the reproducible example requested (I hope that's what you mean?)
structure(list(Site = c("Mylor", "Mylor", "Mylor", "Mylor", "Mylor",
"Mylor", "Mylor", "Mylor", "Mylor", "Mylor"), Trial = c(1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), Location = c("centre", "edge",
"edge", "edge", "edge", "edge", "edge", "centre", "centre", "centre"
), Bait = c("whitefish", "whitefish", "whitefish", "whitefish",
"whitefish", "whitefish", "whitefish", "whitefish", "whitefish",
"whitefish"), ECP = c("yes", "yes", "yes", "yes", "yes", "yes",
"yes", "no", "no", "no"), SSP = c("no", "no", "no", "no", "no",
"no", "no", "no", "no", "no"), KP = c("no", "no", "no", "no",
"no", "no", "no", "no", "no", "no"), OSP = c("no", "no", "no",
"no", "no", "no", "no", "no", "no", "no"), Density =
c("dense_seagrass",
"dense_seagrass", "dense_seagrass", "dense_seagrass",
"dense_seagrass",
"dense_seagrass", "dense_seagrass", "dense_seagrass",
"dense_seagrass",
"dense_seagrass"), Viz = c(1.75, 1.75, 1.75, 1.75, 1.75, 1.75,
1.75, 4.5, 4.5, 4.5), Species = c("sea_sprat", "corkwing_wrasse",
"pollack", "sand_smelt", "unknown_wrasse", "two_spotted_goby",
"unknown_wrasse", "mackerel", "sand_smelt", "mullet"), AJ = c("juv",
"juv", "juv", "adu", "adu", "adu", "adu", "adu", "adu", "adu"
), FG = c("pelagic_neritic", "reef_associated", "pelagic_neritic",
"pelagic_neritic", "reef_associated", "reef_associated",
"reef_associated",
"pelagic_neritic", "pelagic_neritic", "pelagic_neritic"), Max_N =
c(1L,
1L, 2L, 2L, 2L, 2L, 1L, 1L, 26L, 1L)), row.names = c(NA, 10L), class
= "data.frame")
b) so I changed the Species to name as suggested, and it has order some but not others? Changed code to this.
test<-ggplot(all2, aes(x=name, y=log(Max_N 1)))
geom_bar(stat = "identity")
coord_flip()
plot after changing code to above
CodePudding user response:
Acutally if I were you, I will just have a reorder
inside ggplot(aes())
, then you don't need to change anything in your data.
library(tidyverse)
ggplot(all, aes(x = reorder(Species, Max_N), y =log(Max_N 1)))
geom_bar(stat = "identity")
coord_flip() labs(x = "Species", y = "Log(MaxN)")
Note that "unknown_wrasse" is not ordered properly because there is a duplicated record of it in your dataset.