Jack
Jack

Reputation: 857

How to reorder a graph with multiple variable based on one value?

I am trying to reorder the following graph based on the rank of the lowest confidence interval (conf.low). This means that Austria (AU) should be the first country, Bulgaria (BG) the second and Belgium (BE) the third. I know there is a way to do it manually by choosing the order of the country variable but i prefer to find a way to do it automatically since i have 30 countries. Could someone help?

enter image description here

Here is the data and the code:

df= structure(list(cntry = structure(1:3, .Label = c("AU", "BE", 
"BG"), class = "factor"), estimate = c(0.0053, 0.01740, 
0.0036), conf.low = c(-0.0257, 0.0005, 
-0.0006), conf.high = c(0.0365, 0.0343, 
0.0079)), row.names = c(NA, -3L), class = "data.frame")

df %>%
  arrange(estimate) %>%
  mutate(label = replace(round(estimate, 3),cntry==1, '')) %>%
  ggplot(aes(estimate, cntry,label=label)) + 
  geom_point()+
  geom_text(vjust= -1)  + 
  geom_linerange(mapping=aes(xmin=conf.low , xmax=conf.high, y=cntry)) + 
  geom_point(mapping=aes(x=estimate, y=cntry)) 

Upvotes: 2

Views: 111

Answers (1)

Peter
Peter

Reputation: 12699

Using forcats::fct_reorder() you could do this:


library(dplyr)
library(ggplot2)
library(forcats)

df %>%
  arrange(estimate) %>%
  mutate(label = replace(round(estimate, 3), cntry==1, '')) %>%
  ggplot(aes(estimate, fct_reorder(cntry, conf.low, .desc = TRUE),label=label)) + 
  geom_point()+
  geom_text(vjust= -1)  + 
  geom_linerange(mapping=aes(xmin=conf.low , xmax=conf.high, y=cntry)) + 
  geom_point(mapping=aes(x=estimate, y=cntry))+
  ylab("Country")

Created on 2021-04-22 by the reprex package (v2.0.0)

data

df= structure(list(cntry = structure(1:3, .Label = c("AU", "BE", 
                                                     "BG"), class = "factor"), estimate = c(0.0053, 0.01740, 
                                                                                            0.0036), conf.low = c(-0.0257, 0.0005, 
                                                                                                                  -0.0006), conf.high = c(0.0365, 0.0343, 
                                                                                                                                          0.0079)), row.names = c(NA, -3L), class = "data.frame")

Upvotes: 1

Related Questions