Created
January 16, 2023 14:11
-
-
Save ndemengel/e387cb21d3257f8ba94a537dfe3acdce to your computer and use it in GitHub Desktop.
Example of buidling a bar + line chart using Chart.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildLanguageBattleChart({battleData, containerEl, oldLanguage, newLanguage}) { | |
const dates = battleData.map(d => d.date); | |
const newLanguageFiles = battleData.map(d => d.newLanguageFiles); | |
const oldLanguageFiles = battleData.map(d => d.oldLanguageFiles); | |
const filesRatios = battleData.map(d => d.filesRatio * 100); | |
const canvas = document.createElement('canvas'); | |
canvas.style = 'width: 600px; height: 400px'; | |
containerEl.appendChild(canvas); | |
return new Chart(canvas, { | |
data: { | |
datasets: [{ | |
type: 'bar', | |
label: oldLanguage, | |
data: oldLanguageFiles, | |
borderColor: 'rgba(255, 99, 132, 0.2)', | |
backgroundColor: 'rgba(255, 99, 132, 1)', | |
yAxisID: 'y1', | |
order: 1, | |
}, { | |
type: 'bar', | |
label: newLanguage, | |
data: newLanguageFiles, | |
borderColor: 'rgba(54, 162, 235, 0.2)', | |
backgroundColor: 'rgba(54, 162, 235, 1)', | |
yAxisID: 'y1', | |
order: 1, | |
}, { | |
type: 'line', | |
label: `Proportion of ${newLanguage} (%)`, | |
data: filesRatios, | |
borderColor: 'rgba(255, 159, 64, 1)', | |
backgroundColor: 'rgba(255, 159, 64, 1)', | |
yAxisID: 'y2', | |
order: 0, | |
}], | |
labels: dates | |
}, | |
options: { | |
responsive: false, | |
interaction: { | |
mode: 'index', | |
intersect: false, | |
}, | |
stacked: false, | |
plugins: { | |
title: { | |
display: true, | |
text: `${newLanguage}/${oldLanguage} evolution (number of files)` | |
} | |
}, | |
scales: { | |
x: { | |
title: { | |
display: true, | |
text: 'Date' | |
} | |
}, | |
y1: { | |
type: 'logarithmic', | |
display: true, | |
position: 'left', | |
title: { | |
display: true, | |
text: 'Files' | |
} | |
}, | |
y2: { | |
type: 'linear', | |
display: true, | |
position: 'right', | |
min: 0, | |
max: 100, | |
// grid line settings | |
grid: { | |
drawOnChartArea: false, // only want the grid lines for one axis to show up | |
}, | |
title: { | |
display: true, | |
text: `Proportion of ${newLanguage} (%)` | |
} | |
}, | |
} | |
}, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment