why geom_box plot bar does not appear in corect asending order for small numbers

69 Views Asked by At

I am using geom_bar function to create a bar plot using following sample example. The color bar of small values of Area such as 0.006 and 0.003 are does not appear in ascending order instead they shows higher values in graph. Does someone know why its happening and how to fix it? Thanks

library(ggplot2)
ID        <-  c(1,1,2,2,3,3)
Type      <-  c("Bc", "Ea", "Ea","Ra", "Lr","Ram")
Area      <- c(0.15,0.11, 0.0066,0.11,0.0037,0.088)
data.Table <- data.frame(ID ,Type,Area )
p         <- ggplot(dataTable)+ 
         geom_bar(aes(fill=Type, y=Area, x=ID), stat="identity")
print(p)
1

There are 1 best solutions below

9
On BEST ANSWER

To reorder the stacked bars in ascending order by Area you could use reorder(Type,-Area):

library(ggplot2)
ID        <-  c(1,1,2,2,3,3)
Type      <-  c("Bc", "Ea", "Ea","Ra", "Lr","Ram")
Area      <- c(0.15,0.11, 0.0066,0.11,0.0037,0.088)
data.Table <- data.frame(ID ,Type,Area )

p         <- ggplot(data.Table)+ 
  geom_bar(aes(fill=reorder(Type, -Area), y=Area, x=ID), stat="identity")
print(p)

EDIT If the y-axis should show the values of Area for each bar, i.e. the bars should not be stacked on top of each other, but addtionally the bars should not be dodged then the only option I could think of is to overlay the bars using position="identity" (or perhaps position = position_dodge(width = .1) which gives a mix of dodging and overlaying). In that case we have to order the dataset such that the observations with small Area are at the end (per ID) which could be achieved via data.Table[order(ID, -Area),]. Additionally, in that case we don't have to reorder Type:

library(ggplot2)

ID        <-  c(1,1,2,2,3,3)
Type      <-  c("Bc", "Ea", "Ea","Ra", "Lr","Ram")
Area      <- c(0.15,0.11, 0.0066,0.11,0.0037,0.088)
data.Table <- data.frame(ID ,Type,Area )

data.Table01<- data.Table[order(ID, -Area),]
ggplot(data.Table01) + 
  geom_bar(aes(fill=Type, y=Area, x=ID), stat="identity", position = "identity")