Reputation: 33
The ggplot2 manual at http://had.co.nz/ggplot2/scale_manual.html suggests using a structure like:
values = c("8" = "red","4" = "blue","6" = "darkgreen", "10" = "orange")
to assign specific colours to values.
How does one generate this structure from two arrays:
A = c("8","4","6","10"); B = c("red","blue","darkgreen","orange")
I got as far as:
rbind(A,B)
[,1] [,2] [,3] [,4]
A "8" "4" "6" "10"
B "red" "blue" "darkgreen" "orange"
But I am not sure how to turn that into an array of "X" = "Y" assignments.
I realise this is a general R question, not one specific to ggplot2. But I'm tagging it ggplot2 in case it helps someone with the same issue in the future. Any advice welcomed...
Upvotes: 0
Views: 502
Reputation: 60924
This should work:
values = B
names(values) = A
> all.equal(values,
+ c("8" = "red","4" = "blue","6" = "darkgreen", "10" = "orange"))
[1] TRUE
The behavior you are after mimics that of a Python dictionary. There are key
,value
pairs, and referring to a specific key returns the value. In this R example the keys
are the names of the character vector, and the values
are the values inside the vector. For ggplot2 this explicitly couples a key (e.g. "8"
) to a color value ("red"
).
Upvotes: 3