alignment of the axis and data labeles in ggplot

Viewed 61

I took an interesting sample of ggplot here and remade it for my data
My data is excel file

`

col <- c("Low weight", "very low weight", "Extra Very Low weight", "Cesarean section", "premature")
> ORpos <- c(6.8, 4.5,0.4, 4.5, 3.9)
> CI1 <- c(0.6, 0.4, 0, 0.2, 0.4)
> CI2 <- c(74, 56, 32, 20, 2.4)
> ORneg <- c(4.8, 15, 6, 6, 4)
> CI3 <- c(0.6, 0.4, 0, 0.2, 0.4)
> CI4 <- c(56, 43, 21, 10, 5)
> md4 <- data.frame(col,ORpos, CI1, CI2, ORneg, CI3, CI4)
 
plot3 <- ggplot(md4, aes(x = col)) +
  geom_col( 
    aes(y = Orp, fill = 'Orp')) +geom_text(aes(y=Orp, label = paste(Orp, " [", CI1," ; ", CI2, "]", sep = ""), hjust = -1))+
  geom_col( 
    aes(y = -Orn, fill = 'Orn')) + geom_text(aes(y=-Orn, label = paste(Orn, " [", CI3," ; ", CI4, "]", sep = ""), hjust = 1))+
  coord_flip() +
  scale_y_continuous(limits = c(-30, 30))

plot3

But this is where my understanding of R ended completely.
my plot

  1. Why is order my variables in the plot not order as in the table ???

2 What to do to data labels would be on the right and left edges of the plot or at least exactly under each other

1 Answers

For your first issue of reordering you need to transform your character column to factors (as Gregor pointed out) via md4$col = factor(md4$col, levels = unique(md4$col)) or just md4$col = factor(md4$col, levels = md4$col) as apparently you don't have repeating values in your column.

For the second issue as far as I know hjust should be between 0 to 1 for left and right justified text relative to your datapoint respectively, so you may want to set it 0 for your ORpos and 1 for ORneg data and then extend your scales to fit in all text, hope this helps:

md4$col = factor(md4$col, levels = rev(md4$col))

ggplot(md4, aes(x = col)) +
  geom_col( aes(y = ORpos, fill = 'Positive culter')) +
  geom_text(aes(y=7, label = paste(ORpos, " [", CI1,"; ", CI2, "]", sep = " "), hjust = 0))+
  geom_col( aes(y = -ORneg, fill = 'Negative culter')) +
  geom_text(aes(y=-7, label = paste(ORneg, " [", CI3,"; ", CI4, "]", sep = " "), hjust = 1))+
  coord_flip() +
  scale_y_continuous(limits = c(-10, 10), breaks = c(-10:10))
Related