Hi i'm having troubles printing in a alert (by clicking one of the portions), a list of users for a specific answer in chart.js + react here's my chart component
Piechart.js
import React,{ Component } from 'react';
import {Chart} from 'react-chartjs-2';
class Piechart extends Component {
constructor(props){
super(props)
this.chartReference = React.createRef();
this.state = {
data:[]
};
}
async componentDidMount(){
const url = "https://api-tesis-marco.herokuapp.com/api/v1/questiondata/"+this.props.title;
const data = await fetch(url)
.then(response => response.json());
this.setState({data:data});
this.myChart = new Chart(this.chartReference.current,{
type: 'pie',
data:{
labels: this.state.data.map(d=>d.Respuesta),
datasets: [{
data: this.state.data.map(d=>d.porcentaje),
backgroundColor: this.props.colors
}],
},
options: {
title: {
display: true,
text: this.props.title,
fontSize: 20,
fontStyle: 'bold'
},
legend: {
position:'right'
},
onClick: clicked
}
});
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
alert();
}
}
}
render(){
return(
<canvas ref={this.chartReference} />
)
}
}
export default Piechart;
//i having troubles passing the lists data of my request
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
//i don't know what to do here
alert();
}
}
Here is the json response of my request:
Data:
[
{
"Respuesta": "A",
"porcentaje": 7,
"quien": [
"1",
"visita1"
]
},
{
"Respuesta": "B",
"porcentaje": 3,
"quien": [
"coco"
]
},
{
"Respuesta": "C",
"porcentaje": 3,
"quien": [
"Dani3l"
]
},
{
"Respuesta": "D",
"porcentaje": 10,
"quien": [
"Gabi",
"test",
"visita prueba"
]
},
{
"Respuesta": "No ha respondido",
"porcentaje": 76,
"quien": [
"9punto5",
"Colita de algodón",
"KarmenQueen",
"Prueba",
"ancova",
"cehum2",
"chuky",
"dev",
"felipe",
"gabs",
"icom2019",
"invunche",
"john",
"laura",
"marian",
"marti",
"pablazozka",
"prueba",
"test1",
"titicaco",
"visita 1",
"visita test"
]
}
]
in my clicked function how can i pass the "quien" lists for the specific portion of my pie chart?, so in the alert i can print the list of that portion , i'm using this as guide https://jsfiddle.net/u1szh96g/208/ but is difficult for me adapt this to react
well after some mixed tutorials and guides, i came with the solution
Piechart.js:
import React,{ Component } from 'react';
import {Chart} from 'react-chartjs-2';
class Piechart extends Component {
constructor(props){
super(props)
this.chartReference = React.createRef();
this.state = {
data:[]
};
}
async componentDidMount(){
const url = "https://api-tesis-marco.herokuapp.com/api/v1/questiondata/"+this.props.title;
const data = await fetch(url)
.then(response => response.json());
this.setState({data:data});
var datasets = [{data: this.state.data.map(d=>d.Count),
backgroundColor: this.props.colors
},
{
data: this.state.data.map(d=>d.Percent)
},
{
data: this.state.data.map(d=>d.Who)}]
this.myChart = new Chart(this.chartReference.current,{
type: 'pie',
data:{
labels: this.state.data.map(d=>d.Answer),
datasets: [{
data: datasets[0].data,
backgroundColor: datasets[0].backgroundColor
}]
},
options: {
title: {
display: true,
text: this.props.title,
fontSize: 20,
fontStyle: 'bold'
},
legend: {
position:'right'
},
tooltips:{
callbacks: {
title: function(tooltipItem, data) {
return 'Respuesta:'+data['labels'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return 'Total:'+data['datasets'][0]['data'][tooltipItem['index']];
},
afterLabel: function(tooltipItem) {
var dataset = datasets[1];
var total = dataset['data'][tooltipItem['index']]
return '(' + total+ '%)';
}
},
backgroundColor: '#FFF',
titleFontSize: 16,
titleFontColor: '#0066ff',
bodyFontColor: '#000',
bodyFontSize: 14,
displayColors: false
},
onClick: clicked
}
});
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
var idx = element[0]['_index'];
var who = datasets[2].data[idx];
alert(who);
}
}
}
render(){
return(
<canvas ref={this.chartReference} />
)
}
}
export default Piechart;
as you can see i only set an datasets array outside
var datasets = [{
data: this.state.data.map(d=>d.Count),
backgroundColor: this.props.colors
},
{
data: this.state.data.map(d=>d.Percent)
},
{
data: this.state.data.map(d=>d.Who)}]
this contains all the datasets of the request, then in the chart instance i only pass the dataset i want to plot, then for my question, in the clicked function only call the element of the array wich contains the list of users for the specific answer
Cliked function:
function clicked(evt){
var element = this.getElementAtEvent(evt);
if(element[0]){
var idx = element[0]['_index'];
var who = datasets[2].data[idx];
alert(who);
}
}
i made a custom tooltip as well, but i have an issue with this(with the default tooltip is the same) because i use this component to plot 4 piecharts but when i hover the mouse only 2 of the 4 charts show me the tooltip, the 2 chart who shows the tooltip are random (when refresh localhost pick randomly 2 of the 4 charts), and i don't know what is happend or how to fix this, i hope this is usefull to someone
Related
I am trying to hide the legend of my chart created with Chart.js.
According to the official documentation (https://www.chartjs.org/docs/latest/configuration/legend.html), to hide the legend, the display property of the options.display object must be set to false.
I have tried to do it in the following way:
const options = {
legend: {
display: false,
}
};
But it doesn't work, my legend is still there. I even tried this other way, but unfortunately, without success.
const options = {
legend: {
display: false,
labels: {
display: false
}
}
}
};
This is my full code.
import React, { useEffect, useState } from 'react';
import { Line } from "react-chartjs-2";
import numeral from 'numeral';
const options = {
legend: {
display: false,
},
elements: {
point: {
radius: 1,
},
},
maintainAspectRatio: false,
tooltips: {
mode: "index",
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return numeral(tooltipItem.value).format("+0,000");
},
},
},
scales: {
xAxes: [
{
type: "time",
time: {
format: "DD/MM/YY",
tooltipFormat: "ll",
},
},
],
yAxes: [
{
gridLines: {
display: false,
},
ticks: {
callback: function(value, index, values) {
return numeral(value).format("0a");
},
},
},
],
},
};
const buildChartData = (data, casesType = "cases") => {
let chartData = [];
let lastDataPoint;
for(let date in data.cases) {
if (lastDataPoint) {
let newDataPoint = {
x: date,
y: data[casesType][date] - lastDataPoint
}
chartData.push(newDataPoint);
}
lastDataPoint = data[casesType][date];
}
return chartData;
};
function LineGraph({ casesType }) {
const [data, setData] = useState({});
useEffect(() => {
const fetchData = async() => {
await fetch("https://disease.sh/v3/covid-19/historical/all?lastdays=120")
.then ((response) => {
return response.json();
})
.then((data) => {
let chartData = buildChartData(data, casesType);
setData(chartData);
});
};
fetchData();
}, [casesType]);
return (
<div>
{data?.length > 0 && (
<Line
data={{
datasets: [
{
backgroundColor: "rgba(204, 16, 52, 0.5)",
borderColor: "#CC1034",
data: data
},
],
}}
options={options}
/>
)}
</div>
);
}
export default LineGraph;
Could someone help me? Thank you in advance!
PD: Maybe is useful to try to find a solution, but I get 'undefined' in the text of my legend and when I try to change the text like this, the text legend still appearing as 'Undefindex'.
const options = {
legend: {
display: true,
text: 'Hello!'
}
};
As described in the documentation you linked the namespace where the legend is configured is: options.plugins.legend, if you put it there it will work:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}
]
},
options: {
plugins: {
legend: {
display: false
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.js"></script>
</body>
On another note, a big part of your options object is wrong, its in V2 syntax while you are using v3, please take a look at the migration guide
Reason why you get undefined as text in your legend is, is because you dont supply any label argument in your dataset.
in the newest versions this code works fine
const options = {
plugins: {
legend: {
display: false,
},
},
};
return <Doughnut data={data} options={options} />;
Import your options value inside the charts component like so:
const options = {
legend: {
display: false
}
};
<Line data={data} options={options} />
I'm using Nivo bar to represent a user's progress on a budget. I've normalized the data by dividing the category balance by the category goal. Example data.
[{
"category": "Gas",
"budget": 0.24,
"over_budget": 0.0
},
{
"category": "Groceries",
"budget": 1.0,
"over_budget": 0.26
}]
I don't want these values to be used as the label on the chart. I plan to use the actual balance value as the label. I have an endpoint that will return the balance for a category and have attempted the following to use that value:
<ResponsiveBar
...
label={d => this.getDollarAmount(d.value)}
...
>
With the function POC as:
getDollarAmount(value) {
console.log("hitting getDollarAmount")
return 1
};
The log message gets logged 500+ times. My expectation would be that the function would only be hit once for each bar in the chart.
I'm still learning react so this could be something obvious. Thanks in advance!
EDIT - Here's the entire BarChart component:
import axios from 'axios';
import React, { Component } from "react";
import { ResponsiveBar } from '#nivo/bar'
// Nivo theming
const theme = {
axis: {
ticks: {
line: {
stroke: "#e9ecee",
strokeWidth: 40
},
text: {
// fill: "#919eab",
fill: "black",
fontFamily: "BlinkMacSystemFont",
fontSize: 16
}
}
},
grid: {
line: {
stroke: "#e9ecee",
strokeWidth: 5
}
},
legends: {
text: {
fontFamily: "BlinkMacSystemFont"
}
}
};
let budgetStatusAPI = 'http://127.0.0.1:8000/api/budget_status/?auth_user=1&month=2020-02-01';
class BarChart extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
}
this.getDollarAmount = this.getDollarAmount.bind(this);
}
componentDidMount() {
console.log("component did mount")
axios.get(budgetStatusAPI).then(response => {
this.setState({
data: response.data
}, function () {
console.log(this.state.data);
})
});
}
componentDidUpdate() {
console.log("component did update")
}
getDollarAmount(value) {
console.log("hitting getDollarAmount")
console.log(value)
return 1
};
render() {
const hard_data = [
{
"category": "Groceries",
"budget_status": 1.0,
"over_budget": .26,
},
{
"category": "Gas",
"budget_status": .24,
"over_budget": 0.0,
}]
return(
<ResponsiveBar
maxValue={1.5}
markers={[
{
axis: 'x',
value: 1,
lineStyle: { stroke: 'rgba(0, 0, 0, .35)', strokeWidth: 2 },
legend: 'Goal',
legendOrientation: 'horizontal',
legendPosition: 'top'
},
]}
enableGridX={false}
gridXValues={[1]}
enableGridY={false}
data={this.state.data}
// data={hard_data}
keys={['budget_status', 'over_budget']}
indexBy="category"
margin={{ top: 25, right: 130, bottom: 50, left: 125 }}
padding={0.3}
layout="horizontal"
colors={{ scheme: 'set2' }}
theme={theme}
defs={[
{
id: 'dots',
type: 'patternDots',
background: 'inherit',
color: '#38bcb2',
size: 4,
padding: 1,
stagger: true
},
{
id: 'lines',
type: 'patternLines',
background: 'inherit',
color: '#eed312',
rotation: -45,
lineWidth: 6,
spacing: 10
}
]}
borderColor={{ from: 'color', modifiers: [ [ 'darker', 1.6 ] ] }}
axisBottom={null}
label={d => this.getDollarAmount(d.value)}
isInteractive={false}
animate={true}
motionStiffness={90}
motionDamping={15}
/>
)
}
}
export default BarChart;
Reproduced here: https://codesandbox.io/s/nivo-bar-label-issue-k4qek
The multiple calling is happening because the bar chart is calling label function for each animation tick/frame render. If we setup a counter, we'll see with animate prop set to true it will render from 450+ to 550+ times, but if we set the prop animate to false, we'll it renders 6 times which is exactly how many price values are > 0.0.
If you want to avoid all these renders, you'll have to disable animation using animate={false} prop like this:
getDollarAmount(value) {
// Remove every console.log inside this function
return `$${value}`
}
render() {
return (
<ResponsiveBar
animate={false}
label={d => this.getDollarAmount(d.value)}
...
);
}
You can check it running to your cloned CodeSandbox. I have set animate to false and the counter log inside getDollarAmount is calling 6 times. Try to change animate to true and you'll see the 500+- renders.
Also, you don't have to create a function for each label call, you can just pass the getDollarAmount function and let it handle the whole d parameter like this:
getDollarAmount(d) {
// Remove every console.log inside this function
return `$${d.value}`
}
render() {
return (
<ResponsiveBar
animate={false}
label={this.getDollarAmount}
...
);
}
I have a state which is an object containing an array and that array contains an object which looks something like this
[{"tone":"negative","value":0},{"tone":"neutral","value":91},{"tone":"positive","value":9}].
So I want to plot a bar chart using only the values from this array of objects. I want to send these values to another component which can be used to plot bar charts dynamically. But I'm not sure how to do it. can someone please show how to send the values to the barchart component and use them in the barchart as well?
This is the code
state={
analysis: {
tonal: [],
anxiety: []
}
}
Analysis = async () => {
//some api call
const {
...tonalAnalysis
} = result.scores;
const tonalArray = Object.entries(tonalAnalysis).reduce(
(carry, [tone, value]) => [
...carry,
{ tone: tone.toLowerCase(), value: parseInt(value) }
],
[]
);
this.setState({
analysis: { ...this.state.analysis, tonal: tonalArray }
});
console.log("Tonal array" + JSON.stringify(this.state.analysis.tonal)); //console logs `[{"tone":"negative","value":0},{"tone":"neutral","value":91},{"tone":"positive","value":9}]`
};
render(){
return {
<BarCharts/> // confused how to send the values as props here
}
the bar chart component where I will use
import React from "react";
import { Bar } from "react-chartjs-2";
import "./App.css";
class BarCharts extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {
labels: [
negative,
neutral,
positive
],
datasets: [
{
label: "Value plotting",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40] //want to use the values here dynamically. Don't want these static values
}
]
}
};
}
render() {
const options = {
responsive: true,
legend: {
display: false
},
type: "bar"
};
return (
<Bar
data={this.state.data}
width={null}
height={null}
options={options}
/>
);
}
}
export default BarCharts;
You can create a HighChart wrapper component that can be used for any Highchart graphs.
Note:- every time the data set changes you need to destroy and re-render the graph again in order to make the graph reflect changes.
// #flow
import * as React from "react";
import merge from "lodash/merge";
import Highcharts from "highcharts";
import isEqual from "lodash/isEqual";
export type Props = {
config?: Object,
data: Array<any>,
onRendered?: () => void
};
class HighchartWrapper extends React.PureComponent<Props> {
container: ?HTMLElement;
chart: any;
static defaultProps = {
config: {},
onRendered: () => {}
};
componentDidMount() {
this.drawChart(this.props);
}
componentWillReceiveProps(nextProps: Props) {
const data= [...this.props.data];
if (!isEqual(nextProps.config, this.props.config) || !isEqual(nextProps.data, data)) {
this.destroyChart();
this.drawChart(nextProps);
}
}
destroyChart() {
if (this.chart) {
this.chart.destroy();
}
}
componentWillUnmount() {
this.destroyChart();
}
drawChart = (props: Props) => {
const { config: configProp, data, onRendered } = props;
if (this.container) {
let config = merge({}, configProp);
this.chart = new Highcharts.chart(this.container, { ...{ ...config, ...{ series: [...data] } } }, onRendered);
}
};
render() {
return <div ref={ref => (this.container = ref)} />;
}
}
export default HighchartWrapper;
In order use it for BarChart just pass the appropriate bar chart config.
<HighchartWrapper config={{
chart: {
type: "bar"
}
}}
data={[]}
>
Edit
import React from "react";
import BarChart from "./BarChart";
export default function App() {
return (
<div style={{ width: 400, height: 840 }}>
<BarChart
config={{
chart: {
height: 840,
type: "bar"
},
xAxis: {
categories: ["Positive", "Neutral", "Negative" ],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: "Population (millions)",
align: "high"
},
labels: {
overflow: "justify"
}
}
}}
data={[
{
name: "Series Name",
data: [90, 9, 10]
}
]}
/>
</div>
);
}
Just add your desired props in at component declaration :
<BarCharts data={this.state.analysis}/>
And on your BarChart Component you will need to just extract the values from your arrays, this just in case you need the same structure:
...
this.state = {
data: {
labels: [
negative,
neutral,
positive
],
datasets: [
{
label: "Value plotting",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: extractValues(this.props.data)
}
]
}
...
//This method can be reused in a hook or in a lifecycle method to keep data updated.
const extractValues = (data) => {
return data.map( d => d.value);
}
You can map the array so your code would be:
state={
analysis: {
tonal: [],
anxiety: []
}
}
Analysis = async () => {
//some api call
const {
...tonalAnalysis
} = result.scores;
const tonalArray = Object.entries(tonalAnalysis).reduce(
(carry, [tone, value]) => [
...carry,
{ tone: tone.toLowerCase(), value: parseInt(value) }
],
[]
);
this.setState({
analysis: { ...this.state.analysis, tonal: tonalArray }
});
console.log("Tonal array" + JSON.stringify(this.state.analysis.tonal)); //console logs `[{"tone":"negative","value":0},{"tone":"neutral","value":91},{"tone":"positive","value":9}]`
};
render(){
return {
<BarCharts values={this.state.analysis.tonal.map((entry) => entry.value)}/> // confused how to send the values as props here
}
And your barchart would be:
import React from "react";
import { Bar } from "react-chartjs-2";
import "./App.css";
class BarCharts extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {
labels: [
negative,
neutral,
positive
],
datasets: [
{
label: "Value plotting",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: props.values //want to use the values here dynamically. Don't want these static values
}
]
}
};
}
render() {
const options = {
responsive: true,
legend: {
display: false
},
type: "bar"
};
return (
<Bar
data={this.state.data}
width={null}
height={null}
options={options}
/>
);
}
}
export default BarCharts;
I'm attempting to integrate ZingChart as a custom component type in GrapesJs. I've followed some examples and have implemented the following plugin.
blocks.js
import { lineChartRef, chartType } from './consts';
export default (editor, opt = {}) => {
const c = opt;
const bm = editor.BlockManager;
if (c.blocks.indexOf(lineChartRef) >= 0) {
bm.add(lineChartRef, {
label: c.labelLineChart,
content: `
<div data-gjs-type="${chartType}" id="myChart"></div>
`
});
}
};
components.js
import { chartType } from './consts';
export default (editor, opt = {}) => {
const domc = editor.DomComponents;
const defaultType = domc.getType('default');
const defaultModel = defaultType.model;
domc.addType(chartType, {
model: defaultModel.extend(
{
defaults: {
...defaultModel.prototype.defaults,
script: function() {
if (typeof zingchart == 'undefined') {
var script = document.createElement('script');
script.src =
'https://cdn.zingchart.com/zingchart.min.js';
document.body.appendChild(script);
}
}
}
},
{
isComponent: el => {
if (
el.getAttribute &&
el.getAttribute('data-gjs-type') === chartType
) {
return {
type: chartType
};
}
}
}
),
view: {
onRender() {
renderZingChart.bind(this)();
}
}
});
function renderZingChart() {
const data = {
type: 'bar',
title: {
text: 'Data Basics',
fontSize: 24
},
legend: {
draggable: true
},
scaleX: {
// Set scale label
label: { text: 'Days' },
// Convert text on scale indices
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
scaleY: {
label: { text: 'Temperature (°F)' }
},
plot: {
animation: {
effect: 'ANIMATION_EXPAND_BOTTOM',
method: 'ANIMATION_STRONG_EASE_OUT',
sequence: 'ANIMATION_BY_NODE',
speed: 275
}
},
series: [
{
// plot 1 values, linear data
values: [23, 20, 27, 29, 25, 17, 15],
text: 'Week 1'
},
{
// plot 2 values, linear data
values: [35, 42, 33, 49, 35, 47, 35],
text: 'Week 2'
},
{
// plot 2 values, linear data
values: [15, 22, 13, 33, 44, 27, 31],
text: 'Week 3'
}
]
};
const chart = {
id: 'myChart',
data
};
zingchart.render(chart);
}
};
index.js
import grapesjs from 'grapesjs';
import loadBlocks from './blocks';
import loadComponents from './components';
import { lineChartRef } from './consts';
export default grapesjs.plugins.add('fndy-charts', (editor, opts = {}) => {
let c = opts;
let defaults = {
blocks: [lineChartRef],
defaultStyle: 1,
labelLineChart: 'Line Chart'
};
// Load defaults
for (let name in defaults) {
if (!(name in c)) c[name] = defaults[name];
}
loadBlocks(editor, c);
loadComponents(editor, c);
});
consts.js
export const lineChartRef = 'line-chart';
export const chartType = 'chart';
When I add the block to the canvas, it renders, but the ZingChart inside does not. Some things I've tried already:
Verify that the ZingChart render function is being called.
Try moving the renderZingChart function call to different component hooks. Specifically, component:mount, view.init(), and view.onRender().
Move the renderZingChart function call to the script function as a script.onload callback. A similar example can be found here: https://grapesjs.com/docs/modules/Components-js.html#basic-scripts. This does render the ZingChart correctly but doesn't feel correct, and does not allow me to pass in parameters since the script function runs outside the scope of GrapesJs.
I'm running out of ideas so any guidance would be great! Thanks!
I'm making a chart component library with echarts, and the approach for rendering the chart would be similar. The only missing thing I see is element's id. It is an attribute that zing uses to render the chart.
I've made a small example which is obviously not production ready because the id of the block is static. This solves specifically the render problem to make the id dynamic you can do it listening to component:add event and add model id as attribute.
const plugin = editor => {
const {
BlockManager: bm
} = editor;
bm.add("mychart", {
label: "Chart",
content: {
tagName: "div",
attributes: {
id: 'myChart'
},
style: {
width: "300px",
height: "300px"
},
script: function() {
const init = () => {
const data = {
type: "bar",
title: {
text: "Data Basics",
fontSize: 24
},
legend: {
draggable: true
},
scaleX: {
// Set scale label
label: {
text: "Days"
},
// Convert text on scale indices
labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
},
scaleY: {
label: {
text: "Temperature (°F)"
}
},
plot: {
animation: {
effect: "ANIMATION_EXPAND_BOTTOM",
method: "ANIMATION_STRONG_EASE_OUT",
sequence: "ANIMATION_BY_NODE",
speed: 275
}
},
series: [{
// plot 1 values, linear data
values: [23, 20, 27, 29, 25, 17, 15],
text: "Week 1"
},
{
// plot 2 values, linear data
values: [35, 42, 33, 49, 35, 47, 35],
text: "Week 2"
},
{
// plot 2 values, linear data
values: [15, 22, 13, 33, 44, 27, 31],
text: "Week 3"
}
]
};
const chart = {
id: this.id,
data
};
zingchart.render(chart);
};
if (typeof zingchart == "undefined") {
var script = document.createElement("script");
script.onload = init;
script.src = "https://cdn.zingchart.com/zingchart.min.js";
document.body.appendChild(script);
} else {
init();
}
}
}
});
};
const editor = grapesjs.init({
container: "#gjs",
fromElement: true,
height: "100vh",
width: "auto",
storageManager: false,
panels: {
defaults: []
},
plugins: ["gjs-preset-webpage", plugin]
});
You can give a check here the chart is rendering.
Codepen
Hope that's enough, cheers!
I don't think you need to write very complicated code for using Zing charts.I will add a small sample code for making a chart block element , So when you drag and drop the block element then it will make the chart a part of the gjs div of grapesjs .I am using Highcharts.
editor.BlockManager.add('Blockhighcharts', {
label: 'Highchart',
category: 'CHART',
attributes: { class:'gjs-fonts gjs-f-b1' },
content: {
script: function () {
var container = "container"+Math.floor(Math.random() * 100);
$(this).attr("id",container);
$('#gridly_div').append($(this));
var myChart = Highcharts.chart(container, {
chart: {
type: 'bar',
},
title: {
text: 'Fruit Consumption'
},
xAxis: {
categories: ['Apples', 'Bananas', 'Oranges']
},
yAxis: {
title: {
text: 'Fruit eaten'
}
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}, {
name: 'John',
data: [5, 7, 3]
}]
});
The HTML code where the chart will be displayed is as follows.
<div id="gjs" style="height:0px; overflow:hidden;">
<style>
#gjs{
height: 100%;
width: 100%;
margin: 0;
}
</style>
<div id='gridly_div' class="gridly">
</div>
I want to change the backgroundColor of only one record from 'labels' array. In my app 'labels' is set to an array of stringified numbers that come from the database. And I want the biggest number to be, let's say green. The rest should be, let's say, pink.
I don't actually know how to access the background of each instance.
Does anybody know how to do that?
This is what I want to achieve:
This is what I was trying to do but it's just the purest form of nonsense as it doesn't work and it would change the background of the whole chart.
import React from 'react';
import { Bar, Line, Pie, Doughnut } from 'react-chartjs-2';
export default class Chart extends React.Component {
constructor(props) {
super(props);
this.state = {
chartData: {
labels: [],
datasets: [{
label: this.props.label,
data: [],
backgroundColor: '#CD5C94',
}]
}
}
}
static defaultProps = {
displayTitle: true,
}
updateChart = () => {
const newArr = this.props.indexes.map(Number);
const latestRecord = Math.max(...newArr);
let color;
console.log(color)
this.state.chartData.labels.forEach(label => {
if (label == latestRecord) {
this.setState({
chartData: {
datasets: [{
backgroundColor: '#CD5C94',
}]
}
})
} else {
this.setState({
chartData: {
datasets: [{
backgroundColor: '#CD5C94',
}]
}
})
}
})
this.setState({
chartData: {
labels: this.props.indexes, //this is the array of numbers as strings
datasets: [{
label: this.props.label, //this is the label of the chart
data: this.props.results, //this is the array of total travel cost records
// backgroundColor: ,
}]
}
})
}
render() {
return (
<div className="myChart">
<button className="bmi-form__button" onClick={this.updateChart}>DISPLAY CHART DATA</button>
<div className="chart">
<Doughnut
data={this.state.chartData}
width={100}
height={50}
options={{
title: {
display: this.props.displayTitle,
text: this.props.text,
fontSize: 25
}
}
}
/>
</div>
</div>
)
}
}
I have achieved to apply different color for each label like this:
const colorMap = {
'Entertainment': '#FF6384',
'Food': '#36A2EB',
'Gas': '#FFCE56',
'Other': '#38c172'
};
const labels = ['Food', 'Other'];
const colors = labels.map(l => colorMap[l]);
const chartData = {
labels,
datasets: [{
backgroundColor: colors,
borderColor: colors,
data: []
}]
};
<Doughnut data={chartData}/>