David LeBauer
David LeBauer

Reputation: 31741

How to control color of letters in geom_text?

I would like to print a row of letters, with a different color for each letter letter identified by both its color and letter shape, such as:

enter image description here

How can I do this using the ggplot package in R?

I'd like to be able to do something like:

library(ggplot2)
s <- sample(x = c("g", "c", "t", "a"), size = 100, replace = TRUE)

ggplot() + geom_text(aes(seq(s), 1, color = s), label = s)

But I get the error

Error: Incompatible lengths for set aesthetics: label

Is there a way to do this?

Upvotes: 1

Views: 484

Answers (1)

David LeBauer
David LeBauer

Reputation: 31741

Through trial, error, a bit of searching I realized that label can be used as an aesthetic:

s <- s[1:20] ## make shorter for example
ggplot() + geom_text(aes(seq(s), 1, color = s, label = s))

enter image description here

Here is a piece of Art called 'Star Wars DNA' (source)

enter image description here

Upvotes: 6

Related Questions