reorder ggplot columns

Hi there,
I have a df like this :

Sample propMirUp propMirDown

1 S104 0.6024 0.39763
2 S113 0.7922 0.20775
3 S115 1.0000 0.00000
4 S118 0.0000 1.00000
5 S119 0.0006 0.99940
...

I want to plot in a single barplot the proportion of propMirUp + propMirDown

#pivot
table_plots_long <- table_plots %>% pivot_longer(!Sample)

#plot
ggplot( table_plots_long, aes(x = NU1147, y = value, fill = name)) + geom_bar(position= "stack",stat = "identity")

However, I would like this plot ordered by the propMirUp value, and this results in a plot ordered by sample.
How could I overcome that?
Best

Simon

I think you want to use {forcats}, like this:

library(tidyverse)

table_plots <- read_csv(
  
  "Sample, propMirUp, propMirDown
S104, 0.6024, 0.39763
S113, 0.7922, 0.20775
S115, 1.0000, 0.00000
S118, 0.0000, 1.00000
S119, 0.0006, 0.99940"

)
#> Rows: 5 Columns: 3
#> -- Column specification --------------------------------------------------------
#> Delimiter: ","
#> chr (1): Sample
#> dbl (2): propMirUp, propMirDown
#> 
#> i Use `spec()` to retrieve the full column specification for this data.
#> i Specify the column types or set `show_col_types = FALSE` to quiet this message.

table_plots_long <- table_plots %>% 
  mutate(Sample = fct_reorder(Sample, propMirUp)) %>% 
  pivot_longer(!Sample)

ggplot(table_plots_long, aes(x = Sample, y = value, fill = name)) + 
  geom_bar(position = "stack", stat = "identity")

Created on 2022-03-22 by the reprex package (v2.0.1)

That's it, thank you

Simon

And please how could I change colors ?
Best

Simon

library(tidyverse)

table_plots <- read_csv(
  
  "Sample, propMirUp, propMirDown
S104, 0.6024, 0.39763
S113, 0.7922, 0.20775
S115, 1.0000, 0.00000
S118, 0.0000, 1.00000
S119, 0.0006, 0.99940"

)
#> Rows: 5 Columns: 3
#> -- Column specification --------------------------------------------------------
#> Delimiter: ","
#> chr (1): Sample
#> dbl (2): propMirUp, propMirDown
#> 
#> i Use `spec()` to retrieve the full column specification for this data.
#> i Specify the column types or set `show_col_types = FALSE` to quiet this message.

table_plots_long <- table_plots %>% 
  mutate(Sample = fct_reorder(Sample, propMirUp)) %>% 
  pivot_longer(!Sample)

plt <- ggplot(table_plots_long, aes(x = Sample, y = value, fill = name)) + 
  geom_bar(position = "stack", stat = "identity")

# premade...
plt + scale_fill_brewer(palette = "Set1")

# manual...
plt + scale_fill_manual(values = c("propMirDown" = "hotpink", "propMirUp" = "darkgreen"))

Created on 2022-03-22 by the reprex package (v2.0.1)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.