Using R to plot colored jittery text, just for fun.
Introduction
Here’s an Rtistic option using R to plot some text in an original way.
First things first: let’s consider some text. For instance, part of the famous speech by Dr. King:
I have a dream that my four little children
will one day live in a nation,
where they will not be judged by the color of their skin
but by the content of their character.
Let’s put the text in a character vector:
First we are going to plot the text as a single string, collapsing it with some new-line characters "\n":
Notice that we’re using basic coordinates with a center for the plot on (0,0). This helps us identify reference points both in the x-axis and the y-axis for future manipulation of the character strings.
In order to plot each character with a different size and with different coordinates, we need to split the strings into individual characters. To do this we use the almighty function strsplit(). For testing purposes, let’s take one sentence from MLK’s speech. Also, we’ll assign x-axis coordinates by dividing the range of the x-axis (form -1 to 1) in equal parts taking into account the number of characters in the input string:
Now we can add color and modify the size of the characters. In this case we’ll use the rainbow() palette for colors, and the runif() function to generate uniform values to modify the sizes of the letters:
Finally, let’s add some jitter to the y-position. We do this by adding some noise following a normal distribution with mean zero and a small standard deviation via the rnorm() function:
Assembling the plot
Once we have all the necessary elements, we can add the rest of the speech lines, remove the axes, and add a little bit of color to the background. Moreover, to manipulate each line of text (i.e. each element in the speech vector) we break them down with sapply(), so we can loop over each line inside the plot: