1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
import React, { Component } from 'react'
import csv from 'parse-csv'
import C3Chart from 'react-c3js'
import 'c3/c3.css'
import './chart.css'
import {
rainbow, bigRainbow
} from './constants'
class SinglePieChart extends Component {
state = {
keys: [],
data: [],
fields: {},
}
componentDidMount() {
const { payload } = this.props
console.log(payload)
console.log(payload.fields)
const fields = {}
payload.fields.forEach(field => {
const [k, v] = field.split(': ')
fields[k] = v
})
fetch(payload.url, { mode: 'cors' })
.then(r => r.text())
.then(text => {
try {
const keys = text.split('\n')[0].split(',').map(s => s.trim().replace(/"/, ''))
const data = csv.toJSON(text, { headers: { included: true } })
this.setState({ keys, data, fields })
} catch (e) {
console.error("error making json:", payload.url)
console.error(e)
}
})
}
render() {
const { keys, data, fields } = this.state
console.log(keys, data)
const [labelField, numberField] = keys
if (!data.length) return null
const rowsToDisplay = parseInt(fields.Top, 10)
const rows = data.map(row => {
const label = row[labelField]
const number = parseFloat(row[numberField])
return [label, number]
}).sort((a, b) => b[1] - a[1])
let chartRows = rows.slice(0, rowsToDisplay)
let otherCount = rows.slice(rowsToDisplay).reduce((a, b) => a + b[1], 0)
if (otherCount > 0) {
chartRows.push([fields.OtherLabel, otherCount])
}
const height = chartRows.length < 6 ? 316 :
chartRows.length < 10 ? 336 : 356
return (
<div className='chart'>
<div>
<C3Chart
data={{
columns: chartRows,
type: 'pie',
}}
color={{
pattern: chartRows.length < 10 ? rainbow : bigRainbow,
}}
tooltip={{
format: {
value: value => value,
}
}}
size={{
height,
}}
/>
<span className='chartCaption'>{fields.Caption}</span>
</div>
</div>
)
}
}
export default SinglePieChart
|