1
votes

I am using ggplot2 to make a plot with species name as y axis labels, such as:

data_1 <- data.frame(
   name = c("1_Enterococcus faecalis_ab1", "3_Bifidobacterium longum_ab2", "5_Bifidobacterium breve_ab12"),
   value = c(1, 3, 5)
) 
data_2 <- data.frame(
   name = c("1_Enterococcus faecalis_ab1", "3_Bifidobacterium longum_ab2", "5_Bifidobacterium breve_ab12"),
   value = c(3, 5, 3)
)
ggplot()+geom_point(data=data_1,aes(x=value,y=name))+geom_point(data=data_2,aes(x=value,y=name))

I want to make the italic species name in the y labels like 1_Enterococcus faecalis_ab1. I see the answer from R ggplot2 using italics and non-italics in the same category label, but still cannot make it.

Any idea to do it? Thanks

2

2 Answers

3
votes

We could use the ggtext method

library(dplyr)
library(ggtext)
library(stringr)
library(ggplot2)
data %>% 
     mutate(name = str_replace(name, "(\\d+)_([^)]+)_(.*)$", "\\1_*\\2*_\\3")) %>%
     ggplot(aes(value, name)) + 
       geom_point() +
       theme(axis.text.y = element_markdown())
3
votes
library(ggtext)
library(tidyverse)
data %>%
  separate(name, c("num", "binomial", "label"), sep = "_") %>%
  mutate(name_fmt = paste0(num, "_*", binomial, "*_", label)) %>%
  
  ggplot(aes(x=value,y=name_fmt)) + geom_point() +
  theme(axis.text.y = element_markdown())

enter image description here

EDIT - if you have two similarly-formatting tables, it'd be easiest to bind them and apply the code for formatting to that:

bind_rows(data_1, data_2, .id = "src") %>%
  separate(name, c("num", "binomial", "label"), sep = "_") %>%
  mutate(name_fmt = paste0(num, "_*", binomial, "*_", label)) %>%
  
  ggplot(aes(x=value,y=name_fmt, color = src)) + geom_point() +
  theme(axis.text.y = element_markdown())

If the structure is different, I'd suggest applying the formatting to the two data tables separately.