2

I try to build a chart using rCharts and polychart frontend:

dtf <- data.frame(x=c(1, 2, 3, 4, 5), y=c(4, 5, 6, 3, 5), 
              label=c('one', 'two', 'one', 'two', 'two'))
color.mapping <- list(one='#ff2385', two='#229922')
p2 <- rPlot(x='x', y='y', data=dtf, type='point', color='label')
print(p2)

I would like to have a control over the point colors by either using some sort of discrete mapping (like in the example above) or using some other logic. How is that done

EDIT

following the Ramnath's answer I tried to do the following, but I get an empty page:

dtf <- data.frame(x=c(1, 2, 3, 4, 5), y=c(4, 5, 6, 3, 5), 
                  label=c('one', 'two', 'one', 'two', 'two'))

p2 <- rPlot(x='x', y='y', data=dtf, type='point', color='label')

p2$guides(color = list(scale = "#! function(value){
   color_mapping = {one: '#ff2385', two: '#229922'}
   return color_mapping[value];                  
 } !#"))


print(p2)

Resolution upgrading rCharts from github has solved the problem.

Community
  • 1
  • 1
Boris Gorelik
  • 29,945
  • 39
  • 128
  • 170

1 Answers1

2

This is a little complicated in Polychart currently, although we are trying to create a more R friendly solution. But for now, here is the way to set custom scales in Polychart

p2$guides(color = list(scale = "#! function(value){
  color_mapping = {one: '#ff2385', two: '#229922'}
  return color_mapping[value];                  
} !#"))

The idea is to set a scale for the color aesthetic. But instead of using a color palette, you specify a function, which returns a color based on the mapping. You need to wrap the function between #! and !# so that rCharts treats it as a JS literal, and does not stringify it when converting to JSON.

If you are unsure how to specify color_mapping in JSON, you can use the function toJSON to convert your R object. Only caveat is avoid using double quotes inside the function, as they tend to get escaped and as a result cause errors.

Hope this was useful.

Ramnath
  • 54,439
  • 16
  • 125
  • 152
  • First of all, thank you for the answer. However, I couldn't adapt your answer to the code (see the addition to the question). Also, there is no toJSON function in my version of rCharts, but there is toJSON2. – Boris Gorelik Sep 09 '13 at 14:49
  • It works for me. Can you make sure that you have the latest dev version of rCharts installed. You can do that by using `devtools::install_github('rCharts', 'ramnathv', ref = 'dev')` – Ramnath Sep 09 '13 at 15:37
  • 1
    And the `toJSON` function is from the `RJSONIO` package, and you will have to load it directly, if you are using it outside of `rCharts`. – Ramnath Sep 09 '13 at 15:37