5
votes

I am trying to plot a vector data in a histogram-like style. This is always kind of easy, because plot(data, type="h") does exactly what I want. However, there is a problem with the color. My vector data looks like this:

 data = c(1,2,2,3,1,1,2,3,1,2,2,3, ... )

What I want to see, is that each 1 is plotted in one color, each 2 in a different color and each 3 likewise. I tried to achieve that with

 plot(data, type="h", col=c("red","blue","green")

but it failed with R looping over the color vector, so that the first bar was red, the second blue, the third green, the fourth red again and so on.

I am very interessted in general solution, because my data vectors do not always consist of the numbers 1, 2 and 3. There are many cases in which the vector holds the numbers from 1 to 6.

Does anybody know how to solve this problem?

3

3 Answers

11
votes

You would need to create a vector of colors of the same length, like this:

data = c(1,2,2,3,1,1,2,3,1,2,2,3)
colors = c("red","blue","green")
plot(data, type="h", col=colors[data])

This works because colors[data] looks like:

print(colors[data])
#  [1] "red"   "blue"  "blue"  "green" "red"   "red"   "blue"  "green" "red"  
# [10] "blue"  "blue"  "green"
6
votes

try this for general method:

data = c(1,2,2,3,1,1,2,3,1,2,2,3,4,5,6,7,12,3)
colors = rainbow(length(unique(data)))
plot(data, type="h", col=colors[data])
0
votes
 colors = rainbow(length(unique(data)));
 hist(data, col=colors[data]) 

Using mr. lapalme's data (above)