Reputation: 1
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:
Labels are arranged in this order:
I need to arrange the labels in this order:
Does anyone know how to do that?
Upvotes: 0
Views: 1113
Reputation: 12719
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)
Upvotes: 1