Home > Net >  Substituting X-axis ticks and text with percentile rank in ggplot
Substituting X-axis ticks and text with percentile rank in ggplot

Time:05-25

I am currently trying to reproduce the following graph: Plot to be replicated

What I am struggling with is substituting the x-axis ticks and text to be the percentile rank rather than the country ISO (essentially replicating the x-axis in the "Plot to be replicated").

I am currently at the stage in this image: Attempted Replication

I am using the following code:

ggplot(data, aes(x = x, y = y))  
  geom_errorbar(aes(ymax = Cup, ymin = Cdo))   
  labs(x = "Country ISO",
       y = "Transparency Rating",
       title = "Transparency Index with CI")   
  theme_light()   
  theme(panel.grid.major.x = element_blank() ,
        panel.grid.major.y = element_line( size=.05, color="grey") 
  )

I tried to use the options with various inputs but I can seem to make it work:

  theme(axis.ticks.x = ,
        axis.text.x =) 
  )

Some data useful for your replication:

x<-c("AFG","ALB","ITA",
     "IND","AGO","ARE",
     "ATG","BEN","BFA",
     "BGD","BGR","BHR",
     "BHS","BIH","BRB", 
     "BRN","BTN","BWA",
     "CAF","CAN")

y<-c(1:20)
Cup<-y 0.4
Cdo<-y-0.4

data<- data.frame(x,y,Cup,Cdo)

Extra points for those who can also tell me how to add certain specific country names at the right point inside of the plot like in the "Plot to be replicated".

Thank you so much for your help!

CodePudding user response:

Includes selective country labelling:

library(tidyverse)

x <- c(
  "AFG", "ALB", "ITA",
  "IND", "AGO", "ARE",
  "ATG", "BEN", "BFA",
  "BGD", "BGR", "BHR",
  "BHS", "BIH", "BRB",
  "BRN", "BTN", "BWA",
  "CAF", "CAN"
)

y <- c(1:20)
Cup <- y   0.4
Cdo <- y - 0.4

data <- data.frame(x, y, Cup, Cdo) |>
  mutate(rank = percent_rank(y))

labels <- data |>
  filter(x %in% c("ITA", "BGR", "CAN")) # select countries to label

data |>
  ggplot(aes(rank, y))  
  geom_text(aes(label = x), data = labels, nudge_y = -2, angle = -90)  
  geom_errorbar(aes(ymax = Cup, ymin = Cdo))  
  labs(
    x = "Pct Rank of Country ISO",
    y = "Transparency Rating",
    title = "Transparency Index with CI"
  )  
  theme_light()  
  theme(
    panel.grid.major.x = element_blank(),
    panel.grid.major.y = element_line(size = .05, color = "grey")
  )

Created on 2022-05-24 by the reprex package (v2.0.1)

  • Related