as.hexmode(0)
[1] "0"
as.hexmode(127)
[1] "7f"
as.hexmode(255)
[1] "ff"
Colors in R can be defined in many different ways:
colors()
gives all available options#RRGGBBAA
, e.g. #FF0000FF
for opaque red. Here, the max value is “FF” which corresponds to 255.rgb(red, green, blue, alpha)
function (outputs a hex number)hsv(h, s, v, alpha)
function for the HSV color system (also outputs a hex number)palette()
, whose defaults can be changed by the user (e.g. palette("cyan", "blue", "magenta", "red")
)There is a long list of color names R understands, and can be listed using colors()
.
They can be passed directly as characters.
Shades of gray are provided as gray0
/grey0
(white) to gray100
/grey100
(black).
An extra wide PDF with all built-in R colors is available here:
Hexadecimal color codes are characters starting with the pound sign, followed by 4 pairs of hex codes representing Red, Green, Blue, and Alpha values. Since RGB values go from 0 to 255, hex goes from 00 to FF. You can convert decimal to hex using as.hexmode()
:
The last two values for the alpha setting are optional: if not included, defaults to max, i.e. opaque.
rgb(0, 0, 1)
[1] "#0000FF"
Note the default maxColorValue = 1
, set to 255 to use the usual RGB range of 0 to 255:
rgb(0, 0, 255, maxColorValue = 255)
[1] "#0000FF"
Color can also be parameterized using the hue, saturation, and value system (HSV). Each range from 0 to 1.
Simplistically: Hue controls the color. Saturation 1 is max color and 0 is white. Value 1 is max color and 0 is black.
hsv(1, 1, 1)
[1] "#FF0000"
In the following plot, the values around the polar plot represent hue. Moving inwards to the center, saturation changes from 1 to 0. (The plot is produced using the mplot_hsv()
function from the rtemis
package.)
mplot_hsv()
mplot_hsv(v = 0.5)
An easy way to add transparency to any color is using adjustcolor()
:
For example, to get 50% transparent blue:
adjustcolor("blue", alpha.f = 0.5)
[1] "#0000FF80"
“FF” is hex for 255, and “80” in hex is 128, therefore you can also define the above color as “#0000FF80”, i.e. 0 red, 0 green, 255 blue, 128 alpha.