0

I have a problem with re-arrangement of labels when making a forestplot with ggplot 2. Hope someone can help! The problem:

I have made the plot using the following code:

df <- data.frame(t(data.frame(
  c("Remifentanil infusionrate, µg/kg/hour",3.1,-0.2,6.2,0.02),
  c("Propofol infusionsrate, mg/kg/hour",0.3,-0.04,0.7,0.13),
  c("BIS",-1.6,-6.5,5.3,0.72),
  c("Time spent in PACU, min",0.2,-0.3,0.6,0.44))))

library(ggplot2)

ggplot(data=df, aes(x=X1,y=as.numeric(X2),
                    ymin=as.numeric(X3),ymax=as.numeric(X4),
                    label=X5)) + 
   geom_point() + 
   geom_linerange() + 
   ylab("Difference (95% Confidence Interval)") + 
   theme_minimal() + 
   coord_flip() + 
   theme(axis.title.y = element_blank()) + 
   geom_text(aes(y=Inf), hjust=1) + 
   ggtitle("Primary and Secondary Outcomes")

It gives this output:

img

Labels are arranged in this order:

  1. Time spent in PACU, min
  2. Remifentanil infusionrate, µg/kg/hour
  3. Propofol infusionsrate, mg/kg/hour
  4. BIS

I need to arrange the labels in this order:

  1. Remifentanil infusionrate, µg/kg/hour
  2. Propofol infusionsrate, mg/kg/hour
  3. BIS
  4. Time spent in PACU, min

Does anyone know how to do that?

camille
  • 16,432
  • 18
  • 38
  • 60
Maria
  • 1
  • The data frame seems to be of an unconventional format, is this by design? – Peter Dec 18 '21 at 15:25
  • Does this answer your question? [Order discrete x scale by frequency/value](https://stackoverflow.com/questions/3253641/order-discrete-x-scale-by-frequency-value) – camille Dec 18 '21 at 19:06

1 Answers1

1

Reorganise the data. In ggplot order of categorical values is organised by factor, once that is as you wish the rest is taken care of by ggplot.

An additional benefit of tidying up data in the data frame the call to ggplot is less cluttered.

df1 <- data.frame(
  x = c("Remifentanil infusionrate, µg/kg/hour",
           "Propofol infusionsrate, mg/kg/hour",
           "BIS",
           "Time spent in PACU, min"),
  y = c(3.1, 0.3, -1.6, 0.2),
  ymin = c(-0.2, -0.04, -6.5, -0.3),
  ymax = c(6.2, 0.7, 5.3, 0.6),
  label = c(0.02, 0.13, 0.72, 0.44))


df1$x <- factor(df1$x, levels = rev(df1$x))

library(ggplot2)

ggplot(data=df1, aes(x = x, y = y, ymin = ymin, ymax = ymax, label = label)) + 
  geom_point() + 
  geom_linerange() + 
  ylab("Difference (95% Confidence Interval)") + 
  theme_minimal() + 
  coord_flip() + 
  theme(axis.title.y = element_blank()) + 
  geom_text(aes(y=Inf), hjust=1) + 
  ggtitle("Primary and Secondary Outcomes")

Created on 2021-12-18 by the reprex package (v2.0.1)

Peter
  • 11,500
  • 5
  • 21
  • 31