R ggplot2 using italics and non-italics in the same category label

ktm*_*ome 5 format r ggplot2 italic

对于我的 ggplot 图,我想在条形图上标记类别,第一个单词为斜体,而以下单词为非斜体。我希望类别标签如下所示:

葡萄球菌(OTU 1)

链球菌(OTU 300)

我找到了一些示例,expression()其中可以将一些类别标签设为斜体,但我希望能够为许多不同的类别执行此操作。

绘制图的代码如下(但我的数据有更多的条要绘制)。

library(ggplot2)

data <- data.frame(
  bactname = c("Staphylococcaceae", "Moraxella", "Streptococcus", "Acinetobacter"),
  OTUname = c("OTU_1", "OTU_2", "OTU_3", "OTU_4"),
  value = c(-0.5, 0.5, 2, 3)
)

data$name <- paste0(
  data$bactname, " (", data$OTUname, ")"
)
data$name <- factor(
  data$name,
  levels = data$name[order(data$value)], ordered = TRUE
)

ggplot(data, aes(name, value)) + 
  geom_col() + coord_flip()
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 1 月 28 日创建

Cla*_*lke 6

我会使用胶水和 ggtext 包。

library(tidyverse)
library(ggtext)
library(glue)

data <- data.frame(
  bactname = c("Staphylococcaceae", "Moraxella", "Streptococcus", "Acinetobacter"),
  OTUname = c("OTU_1", "OTU_2", "OTU_3", "OTU_4"),
  value = c(-0.5, 0.5, 2, 3)
)

data %>% mutate(
  name = glue("*{bactname}* ({OTUname})"),
  name = fct_reorder(name, value)
) %>%
  ggplot(aes(name, value)) + 
  geom_col() + coord_flip() +
  theme(axis.text.y = element_markdown())
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020 年 1 月 29 日创建


Wei*_*ong 3

您可以创建 s 的向量expression,并将其应用于labels中的参数scale_x_discrete:

labs <- sapply(
  strsplit(as.character(data$name), " "), 
  function(x) parse(text = paste0("italic('", x[1], "')~", x[2]))
)

ggplot(data, aes(name, value)) + 
  geom_col() + coord_flip() +
  scale_x_discrete(labels = labs)
Run Code Online (Sandbox Code Playgroud)

如果标签中有空格,例如OTU 100,您可能需要用波形符替换该空格,例如OTU~100。