R ggplot2在同一类别标签中使用斜体和非斜体 [英] R ggplot2 Using Italics and Non-Italics in the Same Category Label

查看:3494
本文介绍了R ggplot2在同一类别标签中使用斜体和非斜体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的ggplot图,我想在barplot上标记第一个单词斜体的类别,而下面的单词是非斜体的。我想要类别标签如下所示:

Staphylococcacae (OTU 1)

<我已经找到了使用表达式()的例子,我可以在其中使用几个类别标签,但是我会喜欢能够为许多不同的类别做到这一点。
创建一个图的代码如下(但是我的数据有更多的图来绘制)。

$ $ $ $ $ $ $ $ $ $ (数据帧)(bactnames = c(Staphylococcaceae,Moraxella,Streptococcus,Acinetobacter),OTUname = c(OTU_1,OTU_2,OTU_3,OTU_4) ,value = c(-0.5,0.5,2,3))

tmp.data $ bactnames2 < - paste0(tmp.data $ bactnames,(,tmp.data $ OTUname, ))
tmp.data $ finalnames< - factor(tmp.data $ bactnames2,levels = tmp.data $ bactnames2 [order(tmp.data $ value)],ordered = TRUE)
ggplot (tmp.data,aes(finalnames,value))+ geom_bar(stat =identity)+ coord_flip()

任何想法,将不胜感激,让我知道如果我可以澄清任何事情。

解决方案

expression s,并将其应用于 scale_x_discrete 标签参数

  labs < -  sapply(strsplit(as.character(tmp.data $ finalnames),) 
函数(x){
parse(text = paste0(italic(',x [1],')〜,x [2]))
})

ggplot(tmp.data,aes (finalnames,value))+ geom_bar(stat =identity)+
coord_flip()+
scale_x_discrete(labels = labs)

输出:



如果标签中有空格,例如 OTU 100 ,您可能需要用波浪替代该空格。 OTU〜100


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:

Staphylococcacae (OTU 1)

Streptococcus (OTU 300)

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

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

tmp.data$bactnames2 <- paste0(tmp.data$bactnames," (",tmp.data$OTUname,")")
tmp.data$finalnames <- factor(tmp.data$bactnames2,levels=tmp.data$bactnames2[order(tmp.data$value)],ordered=TRUE)
ggplot(tmp.data, aes(finalnames,value)) + geom_bar(stat="identity") + coord_flip()

Any thoughts would be appreciated, and let me know if I can clarify anything.

解决方案

You can make a vector of expressions, and apply it to the labels argument in scale_x_discrete:

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

ggplot(tmp.data, aes(finalnames,value)) + geom_bar(stat="identity") + 
  coord_flip() +
  scale_x_discrete(labels = labs)

Output:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆