'Can I create axis labels with vertical-reading text with ggplot?

enter image description here

I would like to create a plot like in the picture: the x-axis labels should be vertical, with the characters STACKED on top of each other.

I am aware of the rotating function, but I was wondering if this is possible as well.



Solution 1:[1]

Using str_replace_all:

str_vert <- function(x) str_replace_all(x, paste0("(.{1})"), "\\1\n")

example:

library(tidyverse)
data <- tibble(name = c("AAA", "BBB"), value = c(0.3, 0.2))
str_vert <- function(x) str_replace_all(x, paste0("(.{1})"), "\\1\n")

ggplot(data, aes(name, value)) +
  geom_col() +
  scale_x_discrete(label = str_vert)

enter image description here

Solution 2:[2]

library(tidyverse)

data <- tibble(
  name = c("AAA", "BBB"),
  value = c(0.3, 0.2)
)

str_stack <- function(x) {
  x %>% str_split("") %>% map(~ .x %>% paste(collapse = "\n"))
}

data %>%
  ggplot(aes(name, value)) +
    geom_col() +
    scale_x_discrete(label = str_stack)

Created on 2022-04-05 by the reprex package (v2.0.0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 danlooo