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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With