You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Charts中绘制横轴为年月、纵轴为模块标签的图表

How to Create a Google Chart with Month-Year X-Axis and Module Labels Y-Axis

Got it, let's build exactly the chart you're asking for using Google Charts. Based on your data and requirements, a Scatter Chart will work perfectly here—it lets us set the X-axis as formatted dates (like "Mar 2018") and the Y-axis as your module labels. We'll also use the numeric value from your data to adjust the size of each data point (you can tweak this if you prefer a different visual style).


Step 1: Set Up the Basic HTML Structure

First, we need a container for the chart and load the Google Charts library:

<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() {
        // We'll add data and config here
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Step 2: Prepare and Format Your Data

Your data includes module names, dates, and numeric values. Important note: Google Charts uses 0-indexed months (January = 0, March = 2, April = 3)—I've adjusted the date indices in your sample to match the correct month labels:

// Raw data with corrected month indices
const rawData = [
  ['Database Module', new Date(2018, 3, 30), 1], // April 2018 (month index 3)
  ['HR Module', new Date(2018, 1, 4), 1], // February 2018 (month index 1)
  ['Finance Module', new Date(2018, 2, 4), 4], // March 2018 (month index 2)
  ['Operations Module', new Date(2018, 2, 4), 6], // March 2018
  ['PP Module', new Date(2018, 2, 4), 1] // March 2018
];

// Map module names to numeric Y-axis values (Scatter Chart requires numbers for Y-axis)
const modules = [...new Set(rawData.map(row => row[0]))];
const moduleToYValue = modules.reduce((map, mod, index) => {
  map[mod] = index + 1; // Start at 1 to avoid overlapping with chart edges
  return map;
}, {});

// Convert raw data to chart-friendly format: [date, yValue, pointSize, moduleName]
const chartData = rawData.map(row => [
  row[1],
  moduleToYValue[row[0]],
  row[2] * 10, // Scale up values for better point visibility
  row[0]
]);

// Create DataTable and add columns/rows
const data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Module');
data.addColumn('number', 'Size');
data.addColumn('string', 'Module Name');
data.addRows(chartData);

Step 3: Configure Chart Options

This is where we make the X-axis show month-year labels and the Y-axis display your module names:

const options = {
  title: 'Module Metrics by Date',
  hAxis: {
    title: 'Date',
    format: 'MMM yyyy', // Formats dates to "Mar 2018"
    gridlines: {count: 5},
    viewWindow: {
      // Set a range to include all your dates (adjust as needed)
      min: new Date(2018, 0, 1),
      max: new Date(2018, 3, 30)
    }
  },
  vAxis: {
    title: 'Modules',
    ticks: modules.map((mod, index) => ({
      v: index + 1,
      f: mod
    })), // Maps numeric Y values to human-readable module labels
    gridlines: {count: modules.length}
  },
  legend: 'none',
  tooltip: {
    // Custom tooltip to show module name, formatted date, and original value
    formatter: function(row) {
      const date = new Date(row.c[0].v);
      const formattedDate = date.toLocaleDateString('en-US', {month: 'short', year: 'numeric'});
      return `${row.c[3].v}<br>Date: ${formattedDate}<br>Value: ${row.c[2].v / 10}`;
    }
  },
  pointSize: 10 // Base size for data points
};

Step 4: Render the Chart

Add this line inside the drawChart function to render the chart in your container:

const chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);

Full Working Code

Putting it all together, here's the complete code you can copy and run directly:

<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() {
        // Raw data with corrected month indices
        const rawData = [
          ['Database Module', new Date(2018, 3, 30), 1],
          ['HR Module', new Date(2018, 1, 4), 1],
          ['Finance Module', new Date(2018, 2, 4), 4],
          ['Operations Module', new Date(2018, 2, 4), 6],
          ['PP Module', new Date(2018, 2, 4), 1]
        ];

        // Map modules to Y-axis values
        const modules = [...new Set(rawData.map(row => row[0]))];
        const moduleToYValue = modules.reduce((map, mod, index) => {
          map[mod] = index + 1;
          return map;
        }, {});

        // Prepare chart data
        const chartData = rawData.map(row => [
          row[1],
          moduleToYValue[row[0]],
          row[2] * 10,
          row[0]
        ]);

        const data = new google.visualization.DataTable();
        data.addColumn('date', 'Date');
        data.addColumn('number', 'Module');
        data.addColumn('number', 'Size');
        data.addColumn('string', 'Module Name');
        data.addRows(chartData);

        // Chart configuration
        const options = {
          title: 'Module Metrics by Date',
          hAxis: {
            title: 'Date',
            format: 'MMM yyyy',
            gridlines: {count: 5},
            viewWindow: {
              min: new Date(2018, 0, 1),
              max: new Date(2018, 3, 30)
            }
          },
          vAxis: {
            title: 'Modules',
            ticks: modules.map((mod, index) => ({
              v: index + 1,
              f: mod
            })),
            gridlines: {count: modules.length}
          },
          legend: 'none',
          tooltip: {
            formatter: function(row) {
              const date = new Date(row.c[0].v);
              const formattedDate = date.toLocaleDateString('en-US', {month: 'short', year: 'numeric'});
              return `${row.c[3].v}<br>Date: ${formattedDate}<br>Value: ${row.c[2].v / 10}`;
            }
          },
          pointSize: 10
        };

        // Draw the chart
        const chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

Key Notes:

  • Month Indexes: Always remember Google Charts uses 0-indexed months (January = 0, December = 11) to avoid date label mismatches.
  • Chart Type Swap: If you prefer horizontal bars instead of scatter points, you can switch to a BarChart and adjust the data structure—just let me know if you want that variation!
  • Customization: Tweak the pointSize, date format, or tooltip content to match your exact design needs.

内容的提问来源于stack exchange,提问作者rana shekhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:12:49