简体   繁体   中英

How to create user-defined legend in google chart?

I created an google chart. Color represents a weekday, eg, red: Mon, blue: Tue, etc.

How to create a legend to show the meaning of different colors, ie red: Mon, blue: Tue, etc.?

Thank you very much?

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load("current", {packages:["corechart"]});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ["Element", "Density", { role: "style" } ],
        ["2018-01-01", 142, "red"],
        ["2018-01-02", 469, "blue"],
        ["2018-01-03", 436, "green"],
        ["2018-01-04", 430, "yellow"],
        ["2018-01-05", 455, "orange"],
        ["2018-01-06", 252, "brown"],
        ["2018-01-07", 306, "black"],
        ["2018-01-08", 485, "red"],
        ["2018-01-09", 401, "blue"],
      ]);

      var view = new google.visualization.DataView(data);
      view.setColumns([0, 1,
                       { calc: "stringify",
                         sourceColumn: 1,
                         type: "string",
                         role: "annotation" },
                       2]);

      var options = {
         //option information
        title: "Number of data",
        width: 3000,
        height: 6000,
        bar: {groupWidth: "80%"},
        legend: { position: "none" },
      };
      var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
      chart.draw(view, options);
  }
  </script>
<div id="barchart_values" style="width: 900px; height: 300px;"></div>
</html>

build the legend on the chart's "ready" event,
be sure to assign the event listener before drawing the chart...

google.visualization.events.addListener(chart, "ready", buildLegend);

use google's date formatter to get the day of the week (Mon, Tue, etc...)

var formatDay = new google.visualization.DateFormat({
  pattern: "EEE"
});
var weekday = formatDay.formatValue(rowDate);

add a legend marker for each row, until all the days are accounted for,
see following working snippet...

 google.charts.load("current", {packages:["corechart"]}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ["Element", "Density", {type: "string", role: "style"}], ["2018-01-01", 142, "red"], ["2018-01-02", 469, "blue"], ["2018-01-03", 436, "green"], ["2018-01-04", 430, "yellow"], ["2018-01-05", 455, "orange"], ["2018-01-06", 252, "brown"], ["2018-01-07", 306, "black"], ["2018-01-08", 485, "red"], ["2018-01-09", 401, "blue"], ]); var view = new google.visualization.DataView(data); view.setColumns([0, 1, { calc: "stringify", sourceColumn: 1, type: "string", role: "annotation" }, 2]); var options = { //option information title: "Number of data", //width: 3000, //height: 6000, bar: {groupWidth: "80%"}, legend: {position: "none"}, }; var chart = new google.visualization.BarChart(document.getElementById("barchart_values")); // chart ready event google.visualization.events.addListener(chart, "ready", buildLegend); chart.draw(view, options); // build the legend function buildLegend() { // legend container var legend = document.getElementById("legend"); legend.innerHTML = ""; // date format - weekday var formatDay = new google.visualization.DateFormat({ pattern: "EEE", timeZone: 5 }); // add legend marker for each weekday var weekdays = []; for (var i = 0; i < data.getNumberOfRows(); i++) { var rowDate = new Date(data.getValue(i, 0)); var weekday = formatDay.formatValue(rowDate); if (weekdays.indexOf(weekday) === -1) { var markerProps = {}; markerProps.color = data.getValue(i, 2); markerProps.label = weekday; addLegendMarker(markerProps); weekdays.push(weekday); } if (weekdays.length === 7) { break; } } } // add legend marker function addLegendMarker(markerProps) { var legendMarker = document.getElementById("template-legend").innerHTML; for (var handle in markerProps) { if (markerProps.hasOwnProperty(handle)) { legendMarker = legendMarker.replace("{{" + handle + "}}", markerProps[handle]); } } document.getElementById("legend").insertAdjacentHTML("beforeEnd", legendMarker); } } 
 #legend { text-align: center; } .legend-marker { display: inline-block; padding: 4px; } .legend-marker-color { display: inline-block; height: 12px; width: 12px; } 
 <script src="https://www.gstatic.com/charts/loader.js"></script> <div id="legend"></div> <div id="barchart_values"></div> <!-- template for building legend --> <script id="template-legend" type="text/html"> <div class="legend-marker"> <div class="legend-marker-color" style="background-color: {{color}}"></div> <span>{{label}}</span> </div> </script> 

note : the timeZone option is used on the date formatter above,
this is due to the format of the date used in the data table ( YYYY-MM-DD )
this option could be removed if the following format were used instead --> ( MM/DD/YYYY )

running the following snippet reveals each format results in a slightly different date...

 console.log(new Date("2018-01-01")); console.log(new Date("01/01/2018")); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM