Helena
Helena

Reputation: 217

How to change text color in a plot?

Is there any function to change colors of selected text, so that I can display custom colors of text that display anywhere in a plot?

Just an example, if I'd like to change the font of "-Log10adjustedP", I can use bquote

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

Is there a color equivalent to this?

Upvotes: 4

Views: 4822

Answers (2)

jay.sf
jay.sf

Reputation: 73842

Using phantom which doesn't plot the text but leaves space for it. This allows us to do a layer-wise approach which is quite flexible.

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)

Note, that if subsequent letters are longer upwards or downwards to the first un-phantomed text, we better include a phantom of those, otherwise the characters get shifted:

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)

For the title there exists a convenience function ContourFunctions::multicolor.title which internally also uses phantom.

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

enter image description here

Upvotes: 3

Abdur Rohman
Abdur Rohman

Reputation: 2944

An alternative way is to use mtext.

plot(1:20)
mtext(~-Log[10] ~ adjusted~italic, col = "blue")

a simple example of mtext with color

Upvotes: 2

Related Questions