0

I'm trying to do a barplot where entries of the same factor are next to eachother so I can compare (in this example I want to compare the tissue type).

I sort the dataframe but for some reason ggplot does not follow the sorting.

tp <- ms %>% 
  arrange(tissue) %>%
  mutate(tissue=as.factor(tissue))
ggplot(tp) + 
  geom_bar(aes(x=Sample, y=!!sym(cv), fill=tissue), stat="identity") +
  ylab("")
head(tp$tissue)

and I check and i know that tp is sorted

head(tp$tissue) outputs

[1] adjacent adjacent adjacent adjacent adjacent adjacent
Levels: adjacent normal tumor

Matt
  • 7,255
  • 2
  • 12
  • 34
Murd
  • 9
  • 2
  • Can you provide a reproducible example? – Anurag N. Sharma Jun 26 '21 at 02:19
  • ggplot does not use the order of the data frame when drawing a discrete scale. It uses the order of the levels of the factor/chracter values you assign to that axis. It doesn't matter how you `arrange()` the data at all. Since you put `Sample` on the x-axis by default it will sort by `Sample`. try `aes(x=reorder(Sample, tissue, FUN=first), y=!!sym(cv), fill=tissue)` you can use `reorder()` to relevel a factor. See `?reorder` help page. – MrFlick Jun 26 '21 at 02:39

0 Answers0