0

So I'm trying to make a bar chart, it comes out fine, but in the wrong order. under "Patient" I have titles; pre, 1 to 3, 4 to 6, 7 to 9, 10 to 12, 13 to 18, 19 to 24 and 24+ . I want the bars in that exact order, but they are coming up in a completely different order.... any idea how I would keep my data in the order above? Here is the code I'm using

library(readr)
library(ggplot2)
ave_gini_and_shannon_timepoint_groups <- read_csv("~//.R/ave gini and shannon timepoint groups.csv")
ggplot(ave_gini_and_shannon_timepoint_groups, aes(x=Patient, fill=Patient, y=Shannon_T)) +
geom_bar(stat = "identity", width=0.4) +
scale_fill_hue(c = 40) +
theme(legend.position="none") 

TIA!

I've tried using reorder, but it isn't working.

stefan
  • 90,330
  • 6
  • 25
  • 51
Ellie
  • 1
  • 2

1 Answers1

-1

You need to transform your variable in a factor and reorder it, here an example, where a reorder the levels of the variable Species in the data.frame iris.

Code

library(ggplot2)
library(dplyr)
library(forcats)

iris %>% 
  mutate(Species = fct_relevel(Species,"virginica","setosa")) %>% 
  ggplot(aes(Species, Sepal.Length))+
  geom_bar(stat = "identity", width=0.4) +
  scale_fill_hue(c = 40) +
  theme(legend.position="none") 

Output

enter image description here

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
  • I get an error when I try this on my dataset, Does this look right? library(readr) library(ggplot2) library(dplyr) library(forcats) ave_gini_and_shannon_timepoint_groups <- read_csv("~//.R/ave gini and shannon timepoint groups.csv") ave_gini_and_shannon_timepoint_groups %>% mutate(Patient = fct_relevel(Patient,"pre","1 to 3", "4 to 6", "7 to 9", "10 to 12", "13 to 18", "19 to 23", "24+")) %>% ggplot(ave_gini_and_shannon_timepoint_groups, aes(x=Patient, fill=Patient, y=Shannon_all)) + geom_bar(stat = "identity", width=0.4) + scale_fill_hue(c = 40) + theme(legend.position="none") – Ellie Jan 20 '23 at 09:12
  • What error you are getting? – Vinícius Félix Jan 20 '23 at 11:50
  • 1. ave_gini_and_shannon_timepoint_groups %>% mutate(Patient = fct_relevel(Patient, "pre", "1 to 3", "4 to 6", "7 to 9", "10 to 12", "13 to 18", "19 to 23", "24+")) %>% ggplot(ave_gini_and_shannon_timepoint_groups, aes(x = Patient, fill = Patient, y = Shannon_all)) – Ellie Jan 23 '23 at 12:49