Graphics Programs Reference
In-Depth Information
To do this, you need to build a list, or vector in R, of colors. Visit each year
and decide what color to make the corresponding bar. If it's a win for the
United States, specify red. Otherwise, specify gray. Here's the code to
do that:
fill_colors <- c()
for ( i in 1:length(hotdogs$Country) ) {
if (hotdogs$Country[i] == “United States”) {
fill_colors <- c(fill_colors, “#821122”)
} else {
fill_colors <- c(fill_colors, “#cccccc”)
}
}
The first line starts an empty vector named
fill_colors
. You use
c()
to cre-
ate vectors in R.
The next line starts a
for
loop. You can tell R to loop through an index
named
i
from 1 to the number of rows in your
hotdogs
data frame. More
specifically, you can take a single column,
Country
, from the hotdogs data
frame, and find the length. If you were to use
length()
with just hotdogs,
you would get the number of columns, which is
5
in this case, but you want
the number of rows, which is
31
. There is one row for each year from 1980
to 2010, so the loop will execute the code inside the brackets 31 times, and
for each loop, the
i
index will go up one.
Most languages use
0-based arrays or
vectors where
the first item is
referenced with
a 0-index. R,
however, uses
1-based vectors.
So in the first iteration, where
i
equals 1, check if the country in the first
row (that is, winner for 1980) is the United States. If it is, append the color
#821122
, which is a reddish color in hexadecimal form, to
fill_colors
.
Otherwise, append #
cccccc
, which is a light gray.
In 1980, the winners were from the United States, so do the former. The
loop checks 30 more times for the rest of the years. enter
fill_colors
in
the R console to see what you end up with. It's a vector of colors just like
you want.
Pass the
fill_colors
vector in the
col
argument for
barplot()
like so.
barplot(hotdogs$Dogs.eaten, names.arg=hotdogs$Year, col=fill_colors,
border=NA, xlab=”Year”, ylab=”Hot dogs and buns (HDB) eaten”)
The code is the same as before, except you use
fill_colors
instead of “red”
in the
col
argument.
Search WWH ::
Custom Search