R ggplot2 在同一类别标签中使用斜体和非斜体 [英] R ggplot2 using italics and non-italics in the same category label
问题描述
对于我的 ggplot 图,我想在条形图上标记类别,第一个单词是斜体,而后面的单词是非斜体.我希望类别标签如下所示:
For my ggplot figure, I want to label categories on a barplot with the first word being italicized, while the following words are non-italicized. I want the category labels to look like follows:
葡萄球菌 (OTU 1)
链球菌 (OTU 300)
我找到了使用 expression()
的示例,我可以在其中将一些类别标签斜体化,但我希望能够为许多不同的类别执行此操作.
I've found examples using expression()
where I can italicize a few category labels, but I would like to be able to do this for many different categories.
绘制图的代码如下(但我的数据有更多的条要绘制).
The code to make a plot is as follows (but my data has many more bars to plot).
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()
由 reprex 包 (v0.3.0) 于 2020-01-28 创建支持>
Created on 2020-01-28 by the reprex package (v0.3.0)
推荐答案
你可以制作一个 expression
的向量,并将其应用到 labels
参数中>scale_x_discrete:
You can make a vector of expression
s, and apply it to the labels
argument in 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)
如果您的标签中有空格,例如OTU 100
,您可能想用波浪号代替空格,例如OTU~100
.
If you have spaces in your labels e.g. OTU 100
, you may want to substitute a tilde for the space, e.g. OTU~100
.
这篇关于R ggplot2 在同一类别标签中使用斜体和非斜体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!