简体   繁体   中英

how to italics and non-italics the part of y axis labels

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

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())
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())

在此处输入图像描述

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM