Home > Blockchain >  Create character vector with new lines for labels in ggplot
Create character vector with new lines for labels in ggplot

Time:01-08

To create labels for a ggplot graph I am trying to create a character vector that includes a new line in each label.

df <- data.frame(
genotype = c("HAX1", 'ELANE', 'SRP54'),
n = c(3, 5, 7)
 )

labs <- paste0(df$genotype, " n=", df$n)

The problem is that in the graph the labels are too big if written in one line. Is there a way I can include a new line after each genotype to write the n=x below it. End result should look similar to this (stack won't allow me to format this properly due to auto-deletion of spaces)

HAX1

n = 3

Thank you!

ps: this should be used for a donut chart at the end:

df %>% ggpubr::ggdonutchart("n", label = labs, fill = "genotype")

CodePudding user response:

You could add \n to your labs to get a break like this:

df <- data.frame(
  genotype = c("HAX1", 'ELANE', 'SRP54'),
  n = c(3, 5, 7)
)
library(ggpubr)
library(dplyr)
labs <- paste0(df$genotype, "\n n=", df$n)

df %>% 
  ggpubr::ggdonutchart("n", label = labs, fill = "genotype")

Created on 2023-01-07 with reprex v2.0.2

  • Related