This code fetches course enrollment data from a Google Sheet and generates an SVG image of a D3.js pie chart visualizing the data. It uses imported functions to retrieve the data and create the chart.
npm run import -- "course list pie chart"
var importer = require('../Core');
var getDataSheet = importer.import("google sheet array objects");
var d3PieChart = importer.import("d3 pie chart");
function getCourseSVG() {
var docId = '1dAtBQyn5vwStM6ITn7iCpp996Sus26k0bJtbGNlCX2g';
return getDataSheet(docId, 'Courses pie data')
.then(data => data.map(d => ({label: d.subject, value: d.percent})))
.then(values => d3PieChart(values))
}
module.exports = getCourseSVG;
// Import necessary modules and functions
const { getDataSheet, d3PieChart } = require('../Core').import({
googleSheetArrayObjects: 'google sheet array objects',
d3PieChart: 'd3 pie chart',
});
/**
* Retrieves course data from Google Sheets and generates a pie chart SVG string
* @returns {Promise} A promise resolving to the SVG string
*/
function getCourseSVG() {
const docId = '1dAtBQyn5vwStM6ITn7iCpp996Sus26k0bJtbGNlCX2g';
return getDataSheet(docId, 'Courses pie data')
.then((data) => {
// Transform data into suitable format for pie chart
return data.map((d) => ({ label: d.subject, value: d.percent }));
})
.then((values) => {
// Generate pie chart SVG string
return d3PieChart(values);
})
.catch((error) => {
// Log error and return a default SVG string
// TODO: Implement proper error handling
console.error(error);
return '';
});
}
module.exports = getCourseSVG;
This code generates an SVG image of a pie chart visualizing course enrollment data from a Google Sheet.
Here's a breakdown:
Imports:
getDataSheet
for fetching data from a Google Sheet, and d3PieChart
for creating a D3.js pie chart.getCourseSVG
Function:
docId
to the ID of the target Google Sheet.getDataSheet
to fetch data from the specified sheet and named range ('Courses pie data').label
(course subject) and value
(enrollment percentage).d3PieChart
to create a D3.js pie chart based on the transformed data.Export:
getCourseSVG
function, making it available for use in other parts of the application.