LineChart.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import React, { PropTypes } from 'react';
  2. import { VictoryAxis, VictoryChart, VictoryLine } from 'victory';
  3. import { formatBytes, formatNumber } from './../util';
  4. import moment from 'moment';
  5. import simplify from 'simplify-js';
  6. import theme from './../theme';
  7. const _formatIndependentAxis = tick => {
  8. return moment(tick).format('HH:mm:ss');
  9. };
  10. const _formatDependentAxis = (tick, format) => (
  11. format === 'bytes' ?
  12. formatBytes(tick, 1) :
  13. formatNumber(tick, 1)
  14. );
  15. // Uses simplifyJS to simplify the data from the backend (there can be up to
  16. // 8000 points so this step is necessary). Because of the format expectations
  17. // of simplifyJS, we need to convert x's to ints and back to moments.
  18. const _simplify = data => {
  19. if (data.length === 0) return [];
  20. return simplify(
  21. data.map(d => ({x: moment(d.x).valueOf(), y: d.y}))
  22. ).map(d => ({x: moment(d.x), y: d.y}));
  23. }
  24. const styles = {
  25. title: {
  26. fontSize: 22,
  27. fontWeight: 300,
  28. textAlign: 'center',
  29. margin: 0
  30. }
  31. };
  32. const LineChart = ({data, format, title}) => {
  33. return (
  34. <div>
  35. <h1 style={styles.title}>{title}</h1>
  36. <VictoryChart
  37. theme={theme}
  38. height={200}
  39. width={1500}>
  40. <VictoryAxis
  41. scale="time"
  42. tickCount={4}
  43. tickFormat={tick => _formatIndependentAxis(tick)}/>
  44. <VictoryAxis
  45. dependentAxis
  46. scale="linear"
  47. tickCount={3}
  48. tickFormat={tick => _formatDependentAxis(tick, format)} />
  49. <VictoryLine data={_simplify(data)} />
  50. </VictoryChart>
  51. </div>
  52. );
  53. };
  54. LineChart.propTypes = {
  55. data: PropTypes.arrayOf(PropTypes.shape({
  56. x: PropTypes.instanceOf(moment),
  57. y: PropTypes.number
  58. })),
  59. format: PropTypes.oneOf(['bytes', 'number'])
  60. };
  61. LineChart.defaultProps = {
  62. data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(n => ({
  63. x: moment().add(n, 'minutes'),
  64. y: n * 100 * Math.random()
  65. })),
  66. format: 'number'
  67. };
  68. export default LineChart;