Search code examples
rggplot2plotlikert

add label on x-Axis in gglikert with R


I want to create a gglikert() plot and I want to add a label on the x-axis but I can't reach the result i am looking for because gglikert() has no xlab()-argument.

First, lets load some testdata.

library(JWileymisc)
library(ggplot2)
library(data.table)
testdat <- 
structure(list(Var = 1:4, Mean = c(1.55, 1.44, 1.33, 1.22), Low = c("D low", "C low", "B low", "A low"), High = c("D high", "C high", "B high", "A high"), SD = c(0.23, 0.365, 0.43, 0.28)),
 row.names = c(NA, -4L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x0000013a8ae885b0>)

Create the gglikert plot

p <- gglikert("Mean", "Var", "Low", "High", data = testdat, xlim = c(1, 7), title = "My Headline") +
          theme(text = element_text(size = 14), legend.position = "none",
                plot.margin = margin(0.5, 3, 0.5 , 0.5, "cm"),
                plot.title = element_text(hjust = 0.5),
                plot.background =  element_rect(color = "black", size = 1))

Extract the data from the gglikert plot

ggdata <- ggplot_build(p)$data[[1]]

Add the standard deviation

ggdata$SD <- testdat$SD

Add error bars, blue points, and lines

p + geom_errorbar(aes(xmin = Mean - SD, xmax = Mean + SD), width = 0.2, color = 'black') 

p2 <- p + geom_errorbar(aes(xmin = pmax(1, Mean - SD), xmax = pmin(5, Mean + SD)), width = 0.2, color = "black") +
          geom_point(aes(x = Mean, y = Var), color = "cornflowerblue", size = 3)

Try to add label

p2 + xlab(label = "LABELLING")

Likertplot As you can see. The label does not show up in the plot. What can I do?


Solution

  • By default, the plot produced has the theme element axis.title.x set to element_blank(). You can change this back to element_text() to get the result you want:

    p2 + 
      xlab(label = "LABELLING") + 
      theme(axis.title.x = element_text())
    

    enter image description here