Vue ChartJs
https://stackoverflow.com/questions/53646391/vue-chart-js-simple-dot-line-on-bar-chart#
by Huynh Ha
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<div id="vue">
<chart type="line" :data="data" :options="options"></chart>
</div>
Vue
//clone is equivalent of lodash.cloneDeep
//necessary because chart.js messes with the data object, inserting circular references that break Vue's reactivity
function clone(obj){
return JSON.parse(JSON.stringify(obj))
}
// The important part: the Chart component
Vue.component('chart', {
template:`
<canvas></canvas>
`,
props: ['type', 'data', 'options'],
mounted() {
this._chart = new Chart(this.$el, {
type: this.type,
data: clone(this.data),
options: this.options
})
},
watch: {
'data': {
handler(data) {
this._chart.data.labels = data.labels
data.datasets.forEach((dataset, index) => {
for (let key in dataset){
this._chart.data.datasets[index][key] = clone(dataset[key])
}
})
this._chart.update()
},
deep: true
}
}
})
// simulate the API to get data points
const retrieveData = () => [
{ val: 1, freq: 0.15 },
{ val: 2, freq: 0.25 },
{ val: 3, freq: 0.3 },
{ val: 4, freq: 0.2 },
{ val: 5, freq: 0.1 },
{ val: 6, freq: 0.45 }
]
//App setup
new Vue({
el:'#vue',
data() {
// fetch your data here, return array of JSON { val, freg }
const dataPoints = retrieveData() || [];
// calculate expected value = sum( val * freq ) each i in dataPoints
const expectedValue = dataPoints.reduce((cur, { val, freq }) => cur + val * freq, 0).toFixed(4);
return {
data: {
datasets: [{
label: 'Frequency Data',
data: dataPoints.map(({ val, freq }) => ({
x: val,
y: freq
})),
backgroundColor: 'rgba(72, 202, 59, 0.4)',
borderColor: 'rgba(72, 202, 59, 1)'
}, {
label: 'Expected Value',
type: 'bubble',
data: [{
x: expectedValue,
y: 0,
r: 8 // radius
}],
backgroundColor: 'rgba(255, 68, 0, 0.4)',
borderColor: 'rgba(255, 68,...