0
0
R Programmingprogramming~5 mins

Color scales and palettes in R Programming

Choose your learning style9 modes available
Introduction

Color scales and palettes help you pick colors to show data clearly and nicely in graphs.

You want to make a bar chart with different colors for each bar.
You need to show temperature changes using colors from blue to red.
You want to highlight groups in a scatter plot with distinct colors.
You are creating a heatmap and want smooth color changes.
You want your graph colors to look good and be easy to understand.
Syntax
R Programming
scale_color_gradient(low = "color1", high = "color2")
scale_fill_gradient(low = "color1", high = "color2")
scale_color_manual(values = c("color1", "color2", ...))
scale_fill_manual(values = c("color1", "color2", ...))

scale_color_* changes colors of points, lines, or text.

scale_fill_* changes colors of filled areas like bars or tiles.

Examples
This makes points colored from blue (low hp) to red (high hp).
R Programming
library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg, color = hp)) +
  geom_point() +
  scale_color_gradient(low = "blue", high = "red")
This sets specific colors for bars with 4, 6, and 8 cylinders.
R Programming
ggplot(mtcars, aes(x = factor(cyl), fill = factor(cyl))) +
  geom_bar() +
  scale_fill_manual(values = c("4" = "green", "6" = "orange", "8" = "purple"))
Sample Program

This program draws a scatter plot where points change color from light blue to dark red based on horsepower.

R Programming
library(ggplot2)
# Scatter plot with color gradient
p <- ggplot(mtcars, aes(x = wt, y = mpg, color = hp)) +
  geom_point(size = 3) +
  scale_color_gradient(low = "lightblue", high = "darkred") +
  ggtitle("Car weight vs MPG colored by horsepower")
print(p)
OutputSuccess
Important Notes

Use named colors like "red", "blue", or hex codes like "#FF0000".

Color gradients are good for continuous data, manual palettes for categories.

Try colorblind-friendly palettes for better accessibility.

Summary

Color scales help show data differences clearly using colors.

Use scale_color_gradient for smooth color changes.

Use scale_fill_manual or scale_color_manual to pick exact colors.