问题
I am dynamically creating a couple of gvisScatterChart
s. I want to define the colors of each line, which I can do using series and the color attribute. There is nothing like an order or a fix number by which I can predefine the colors. So I want to create an array of attributes parallel to my colors and just place it at series=myColors
.
The problem is that gVis expects a string like:
series="[{color: 'black', visibleInLegend: false}]",
As soon as I create a string using the paste
function gVis doesn't accept them any more and just shows a blank page as chart. (Even when marking the " using \")
Is this a bug or am I doing something wrong?
回答1:
This is not a bug, just as said in the help it expects a JSON string so you need to build JSON string.
Using RJSONIO
you can build the JSON option using toJSON
library(googleVis)
library(RJSONIO)
myColor <- 'grey' ## my dynamic color, here I fix but you can read it ,e.g
## from a chart config file or whatever you want
isLegend <- TRUE ## a boolean value
myseriesOptions <- toJSON(list(list(color=myColor),list(visibleInLegend=isLegend)))
For example
Scatter2 <- gvisScatterChart(women,
options=list(legend="none",
lineWidth=2, pointSize=0,
title="Women", vAxis="{title:'weight (lbs)'}",
hAxis="{title:'height (in)'}",
width=300, height=300,
series = myseriesOptions ))
plot(Scatter2)
PS : We can use fromJSON
to get the R form of the string to construct, e.g
fromJSON("{title:'mytitle'}") ## the ouptut is a list
$itl
NULL
cat(toJSON(list(title='mytitle'))) ## I construct my list and I use toJSON
## I get my origin json form
{
"title": "mytitle"
}
来源:https://stackoverflow.com/questions/14080344/gvisscatterchart-define-series-dynamically