[SOLVED] alignment of the axis and data labeles in ggplot

Issue

This Content is from Stack Overflow. Question asked by LLA

I took an interesting sample of ggplot here and remade it for my data
Ma data is excel file
15 obs. of 9 var.

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 = "right"))+
  geom_col( 
    aes(y = -Orn, fill = 'Orn')) + geom_text(aes(y=-Orn, label = paste(Orn, " [", CI3," ; ", CI4, "]", sep = ""), hjust = "left"))+
  coord_flip() +
  scale_y_continuous()
plot3

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

  1. Why is my variables in the schedule not in order ???

2 What should I write for the axis, so that they are aligned. The source was scale_y_continious (?), but I could not cope with an example.

3 And what to do so that data labels were on the right and left edges of the plot.



Solution

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))


This Question was asked in StackOverflow by LLA and Answered by MeisamYSF It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?