R ggplot2 Using Italics and Non-Italics in the Same Category Label

此生再无相见时 提交于 2020-01-15 04:58:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/39282293/r-ggplot2-using-italics-and-non-italics-in-the-same-category-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!