RColorBrewer is an R package that allows users to create colourful graphs with pre-made color palettes that visualize data in a clear and distinguishable manner. There are 3 categories of palettes: qualitative, diverging, and sequential.
- Qualitative palettes employ different hues to create visual differences between classes. These palettes are suggested for nominal or categorical data sets.
- Sequential palettes progress from light to dark. When used with interval data, light colors represent low data values and dark colors represent high data values.
- Diverging palettes are composed of darker colors of contrasting hues on the high and low extremes and lighter colors in the middle.
The palettes are composed of 8-12 distinct colors, but if you have more than 12 categories to graph, you can use the
colorRampPalette() function with any of the sequential or diverging palettes. This ramps the color at the necessary interval to create as many hues as your data calls for.
Below are a few examples using RColorBrewer and Plotly! The code for the first example is provided below and the full R scripts and data for the second and third examples are available here.
1) Bar Graph with the Paired palette:
First, add the libraries:
Add x & y data and define the type of graph as “bar”. To use RColorBrewer define
marker = list(color = brewer.pal(n_palette, "Palette_Name")
n_palette is the number of colors from the palette that you want to use in the graph.
Finally, specify any layout information and send to Plotly!
2) Scatterplot with
colorRampPalette() and the Spectral palette:
The key here is to set
n_palette is the number of colors from the palette that you want to use and
n_plot is the number of colors you want in your plot. For this example, we’ll use the Spectral palette. The Spectral palette has a max of 11 colors. We’ll use the full palette and we want each of the 100 points to be a different color so:
marker = list(color = colorRampPalette(brewer.pal(11,"Spectral"))(100))
3) Line Graph with ggplot syntax:
You can also use RColorBrewer with ggplot with the command
scale_colour_brewer(palette = "Palette_Name"). You can view the full script for this example, but the generic syntax is:
ggplot(data = Your_Data,
aes(x = X_Variable,
y = Y_Variable,
group = Group_Variable,
colour = Group_Variable)) +
scale_colour_brewer(palette = "Palette_Name")
py$ggplotly(kwargs = list(filename = "Your_Filename",
fileopt = "overwrite")