i have below data.frame called df
. problem has order on y-axis. want names on y-axis ordered according variable depth
.
if this:
ggplot(df,aes(x=factor(name),y=depth)) + geom_bar(stat='identity') + coord_flip() + labs(y='depth',x='species')
i got graph1
below not ordered. therefore followed instructions found here, ordered levels of factor name
according depth:
df2=df[order(df$depth),] df2$name=factor(df2$name,levels=df2$name) ggplot(df2,aes(x=factor(name),y=depth)) + geom_bar(stat='identity') + coord_flip() + labs(y='depth',x='species')
i got graph2
below. next step me color bars differently depending on mut
variable.
ggplot(df2,aes(x=factor(name),y=depth)) + geom_bar(stat='identity',data=subset(df2,df2$mut==2),fill='red') + geom_bar(stat='identity',data=subset(df2,df2$mut==1),fill='blue') + coord_flip() + labs(y='depth',x='species')
and got graph3
not ordered anymore!!
how can produce graph3 respecting order displayed in graph2
name depth mut x 25 a_rubrocinctus_ga070 8 2 -0.033318659 9 a_omanensis_ga051 10 2 -0.020387101 4 a_latifasciatus_ga083 12 1 -0.005645811 27 a_frenatus_ga068 12 1 -0.024190876 13 a_percula_ga017 15 1 0.034591721 14 a_percula_ga039 15 2 0.034591721 15 a_percula_ga053 15 2 0.034591721 16 a_ocellaris_ga009 15 1 0.052042539 17 a_ocellaris_ga021 15 1 0.052042539 24 a_ephippium_ga057 15 2 -0.016859412 20 p_biaculeatus_ga008 16 1 -0.014466403 21 p_biaculeatus_ga025 16 1 -0.014466403 22 p_biaculeatus_ga065 16 1 -0.014466403 23 a_melanopus_ga034 18 2 -0.026915545 26 a_melanopus_ga012 18 2 -0.026915545 12 a_sandaracinos_ga018 20 1 0.055839755 6 a_nigripes_ga055 25 1 0.023420045 8 a_sebae_ga029 25 1 0.021767793 11 a_akallopisos_ga067 25 1 0.043272525 28 a_akallopisos_ga072 25 1 0.043272525 34 a_akindynos_ga032 25 1 -0.020707141 1 a_polymnus_ga004 30 1 0.030902254 3 a_allardi_ga033 30 1 -0.020277664 5 a_bicinctus_ga036 30 1 -0.025354572 7 a_polymnus_ga019 30 1 0.030902254 32 a_chrysopterus_ga040 30 1 -0.022402365 33 a_chrysopterus_ga031 30 1 -0.022402365 35 a_perideraion_ga020 38 1 0.052830132 36 a_perideraion_ga015 38 1 0.052830132 2 a_tricinctus_ga058 40 1 -0.016230301 18 a_chrysogaster_ga080 40 1 0.012608835 19 a_chrysogaster_ga077 40 1 0.012608835 10 a_latezonatus_ga023 45 1 -0.010718845 31 a_mccullochi_ga056 45 1 -0.031664307 29 a_clarkii_ga044 60 1 -0.014474658 30 a_clarkii_ga010 60 1 -0.014474658
graph1 graph2
graph3
thank you!
as have variable mut
in data determines level each observation belongs, don't need use geom_bar()
twice subset. add fill=factor(mut)
inside aes()
, use df2 ordered data. bars in correct order , color made automatically.
ggplot(df2,aes(x=factor(name),y=depth,fill=factor(mut))) + geom_bar(stat='identity') + coord_flip() + labs(y='depth',x='species')
the same result can achieved original dataframe df
, function reorder()
inside aes()
x values.
ggplot(df,aes(x=reorder(name,depth),y=depth,fill=factor(mut))) + geom_bar(stat='identity') + coord_flip() + labs(y='depth',x='species')