首页 > 解决方案 > 如何更改绘图中的文本颜色?

问题描述

是否有任何功能可以更改所选文本的颜色,以便我可以显示显示在绘图中任何位置的自定义文本颜色?

只是一个例子,如果我想改变“-Log10adjustedP”的字体,我可以使用bquote

bquote(~-Log[10] ~ adjusted~italic(P))

有没有color等价的?

标签: rplot

解决方案


使用phantomwhich 不会绘制文本,但会为它留出空间。这使我们能够进行非常灵活的分层方法。

plot(dnorm(seq(-5, 5, .01)), type="l")

text(0, .35, bquote(.("Lorem ")*phantom(.("ipsum"))), col=1, adj=0)
text(0, .35, bquote(phantom(.("Lorem "))*"ipsum"), col=2, adj=0)
text(0, .35, bquote(phantom(.("Lorem ipsum "))*"dolor"), col=3, adj=0)
text(0, .35, bquote(phantom(.("Lorem ipsum dolor "))*"sit "), col=4, adj=0)
text(0, .35, bquote(phantom(.("Lorem ipsum dolor sit "))*"amet."), col=5, adj=0)

text(650, .35, bquote(~-Log~phantom(.[10])~phantom(adjusted~italic(P))), col="#000000", adj=0)
text(650, .35, bquote(~phantom(-Log)[10]~phantom(adjusted~italic(P))), col="#ff0000", adj=0)
text(650, .35, bquote(~phantom(-Log[10])~adjusted~phantom(italic(P))), col="#00ff00", adj=0)
text(650, .35, bquote(~phantom(-Log[10]~adjusted)~italic(P)), col="#0000ff", adj=0)

请注意,如果后续字母比第一个 unedphantom文本向上或向下更长,我们最好包含其中的一个phantom,否则字符会移位:

text(75, .2, bquote("c"*phantom("ol")), col=1, adj=0, font=2, cex=1.5)
text(75, .2, bquote(phantom("c")*"o"*phantom("l")), col=2, adj=0, font=2, cex=1.5)
text(75, .2, bquote(phantom("co")*"l"), col=3, adj=0, font=2, cex=1.5)
text(75, .2, bquote(phantom("col")*"o"), col=4, adj=0, font=2, cex=1.5)
text(75, .2, bquote(phantom("colo")*"r"), col=5, adj=0, font=2, cex=1.5)
text(75, .2, bquote(phantom("color")*"f"), col=6, adj=0, font=2, cex=1.5)
text(75, .2, bquote(phantom("colorf")*"u"), col=7, adj=0, font=2, cex=1.5)
text(75, .2, bquote(phantom("colorfu")*"l"), col=8, adj=0, font=2, cex=1.5)

因为title存在一个便利功能ContourFunctions::multicolor.title,它在内部也使用phantom.

ContourFunctions::multicolor.title(c("This ","could ", "be ", "your ", "title"), 1:5)

在此处输入图像描述


推荐阅读