Beginner's guide to R: Painless data visualization

Part 4 of our hands-on guide covers simple graphics, bar graphs and more complex charts.

For many more details, check the help command on a palette such as:

?rainbow

   Using color
Using three colors in the R rainbow palette.

Now that you've got a list of colors, how do you get them in your graphic? Here's one way. Say you're drawing a 3-bar barchart using ggplot() and want to use 3 colors from the rainbow palette. You can create a 3-color vector like:

mycolors <- rainbow(3)

Or for the heat.colors pallette:

mycolors <- heat.colors(3)

Now instead of using the geom_bar() function without any arguments, add fill=mycolors to geombar() like this:

ggplot(mtcars, aes(x=factor(cyl))) + geom_bar(fill=mycolors)

You don't need to put your list of colors in a separate variable, by the way; you can merge it all in a single line of code such as:

ggplot(mtcars, aes(x=factor(cyl))) + geom_bar(fill=rainbow(3))

But it may be easier to separate the colors out if you want to create your own list of colors instead of using one of the defaults.

The basic R plotting functions can also accept a vector of colors, such as:

barplot(BOD$demand, col=rainbow(6))

You can use a single color if you want all the items to be one color (but not monochrome), such as

barplot(BOD$demand, col="royalblue3")

Chances are, you'll want to use color to show certain characteristics of your data, as opposed to simply assigning random colors in a graphic. That goes a bit beyond beginning R, but to give one example, say you've got a vector of test scores:

testscores <- c(96, 71, 85, 92, 82, 78, 72, 81, 68, 61, 78, 86, 90)

You can do a simple barplot of those scores like this:

barplot(testscores)

And you can make all the bars blue like this:

barplot(testscores, col="blue")

Join the newsletter!

Or

Sign up to gain exclusive access to email subscriptions, event invitations, competitions, giveaways, and much more.

Membership is free, and your security and privacy remain protected. View our privacy policy before signing up.

Error: Please check your email address.

More about SimpleTest

Show Comments
[]