Set colors on google piechart via dataTable JSON

﹥>﹥吖頭↗ 提交于 2020-01-06 07:17:11

问题


I am using the chartWrapper to pull in some JSON. I am wondering how I would go about settings the colours for each segment on the piechart.

//draw the channel summary data
 $.getJSON("@Url.Action("SummaryData", new { id = Model.Id })", function(data) {
     var channelChartWrapper = new window.google.visualization.ChartWrapper({
         chartType: "PieChart",
         dataTable: data,
         options: {
             title: "Title here"
         },
         containerId: "summary-chart",
     });
     channelChartWrapper.draw();
 });

the data returned by the controller looks like this;

{
   "cols":[
      {
         "id":"",
         "label":"Channel",
         "type":"string",
         "pattern":""
      },
      {
         "id":"",
         "label":"Value",
         "type":"number",
         "pattern":""
      }
   ],
   "rows":[
      {
         "c":[
            {
               "v":"A",
               "f":null
            },
            {
               "v":17,
               "f":null
            }
         ]
      },
      {
         "c":[
            {
               "v":"B",
               "f":null
            },
            {
               "v":208,
               "f":null
            }
         ]
      },
      {
         "c":[
            {
               "v":"C",
               "f":null
            },
            {
               "v":4,
               "f":null
            }
         ]
      },
      {
         "c":[
            {
               "v":"D",
               "f":null
            },
            {
               "v":2,
               "f":null
            }
         ]
      }
   ]
}

I have tried various p: { style: "color: pink" } additions to the cells but with no luck. I can get colours using the colors property on the chart, but this isn't going to work for me as the colour is specifc to the data.


回答1:


It turns out that you can't set colours for charts (different story for tables) in the DataTable/JSON explicitly. However, you can hack around it slightly.

{
   cols:[...,]
   rows:[...,]
   p:{
      colors: ["#ffcc00","#ff0000",...]
   }
}

Then in the javascript;

$.getJSON("@Url.Action("SummaryData", new { id = Model.Id })", function(data) {
     var channelChartWrapper = new window.google.visualization.ChartWrapper({
         chartType: "PieChart",
         dataTable: data,
         options: {
             title: "Title here",
             colors: data.p.colors
         },
         containerId: "summary-chart",
     });
     channelChartWrapper.draw();
 });


来源:https://stackoverflow.com/questions/13064929/set-colors-on-google-piechart-via-datatable-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!