Related
I'm trying to export a chart created with chartjs without an actual site it's just a node backend app that creates the chart, I then need to export it and send it to slack api.
I figured I would try to create a virtual dom and then export from there but is it not working. I'm open to other approaches or fixes to this code. I'm getting an error that says window is undefined, but if I console.log(window) it says it's a window object, and everything looks normal.
const JSDOM = require("jsdom");
const Chart = require("chart.js");
const dom = new JSDOM.JSDOM(`<!DOCTYPE html><canvas id="myChart" width="400" height="400"></canvas>`);
const canvas = dom.window.document.getElementById('myChart');
const ctx = canvas.getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Standing costs', 'Running costs'],
datasets: [{
label: 'Washing and cleaning',
data: [0, 8],
backgroundColor: '#22aa99'
}, {
label: 'Traffic tickets',
data: [0, 2],
backgroundColor: '#994499'
}, {
label: 'Tolls',
data: [0, 1],
backgroundColor: '#316395'
}, {
label: 'Parking',
data: [5, 2],
backgroundColor: '#b82e2e'
}, {
label: 'Car tax',
data: [0, 1],
backgroundColor: '#66aa00'
}, {
label: 'Repairs and improvements',
data: [0, 2],
backgroundColor: '#dd4477'
}, {
label: 'Maintenance',
data: [6, 1],
backgroundColor: '#0099c6'
}, {
label: 'Inspection',
data: [0, 2],
backgroundColor: '#990099'
}, {
label: 'Loan interest',
data: [0, 3],
backgroundColor: '#109618'
}, {
label: 'Depreciation of the vehicle',
data: [0, 2],
backgroundColor: '#109618'
}, {
label: 'Fuel',
data: [0, 1],
backgroundColor: '#dc3912'
}, {
label: 'Insurance and Breakdown cover',
data: [4, 0],
backgroundColor: '#3366cc'
}]
},
options: {
onAnimationComplete: animationDone,
responsive: false,
legend: {
position: 'right'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
});
function animationDone() {
return canvas.toDataUrl("image/jpg");
}
I just want an image file or url that I can send to slack api.
Use chartjs-node-canvas, this is a Node JS renderer for Chart.js using canvas.
It provides and alternative to chartjs-node that does not require jsdom (or the global variables that this requires) and allows chartJS as a peer dependency, so you can manage its version yourself.
This is how it will work with your code:
const { CanvasRenderService } = require('chartjs-node-canvas');
const width = 400;
const height = 400;
const chartCallback = (ChartJS) => {
// Global config example: https://www.chartjs.org/docs/latest/configuration/
ChartJS.defaults.global.elements.rectangle.borderWidth = 2;
// Global plugin example: https://www.chartjs.org/docs/latest/developers/plugins.html
ChartJS.plugins.register({
// plugin implementation
});
// New chart type example: https://www.chartjs.org/docs/latest/developers/charts.html
ChartJS.controllers.MyType = ChartJS.DatasetController.extend({
// chart implementation
});
};
const canvasRenderService = new CanvasRenderService(width, height, chartCallback);
(async () => {
const configuration = {
type: 'line',
data: {
labels: ['Standing costs', 'Running costs'],
datasets: [{
label: 'Washing and cleaning',
data: [0, 8],
backgroundColor: '#22aa99'
}, {
label: 'Traffic tickets',
data: [0, 2],
backgroundColor: '#994499'
}, {
label: 'Tolls',
data: [0, 1],
backgroundColor: '#316395'
}, {
label: 'Parking',
data: [5, 2],
backgroundColor: '#b82e2e'
}, {
label: 'Car tax',
data: [0, 1],
backgroundColor: '#66aa00'
}, {
label: 'Repairs and improvements',
data: [0, 2],
backgroundColor: '#dd4477'
}, {
label: 'Maintenance',
data: [6, 1],
backgroundColor: '#0099c6'
}, {
label: 'Inspection',
data: [0, 2],
backgroundColor: '#990099'
}, {
label: 'Loan interest',
data: [0, 3],
backgroundColor: '#109618'
}, {
label: 'Depreciation of the vehicle',
data: [0, 2],
backgroundColor: '#109618'
}, {
label: 'Fuel',
data: [0, 1],
backgroundColor: '#dc3912'
}, {
label: 'Insurance and Breakdown cover',
data: [4, 0],
backgroundColor: '#3366cc'
}]
},
options: {
responsive: false,
legend: {
position: 'right'
},
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
};
const dataUrl = await canvasRenderService.renderToDataURL(configuration);
})();
dataUrl variable will contain the image you can pass to Slack API
I am currently on a React project and the data being sent from the backend is being modified as it arrives on the frontend. I'm probably missing something really stupid but I cannot figure out where it's going bad for god's sake.
The frontend component
import React from 'react';
//.. import bunch of other things
const styles = theme => ({
root: {},
sectionTitle: {
margin: '20px 0 35px 0'
},
sectionTitleNoTop: {
margin: '0 0 35px 0'
},
gap50: {
margin: 50
}
});
class RankingsPage extends React.Component {
state = {
tableData: null,
tableDataEarnings: null,
barData: null,
barDataEarnings: null,
tableError: ''
};
constructor(props) {
super(props);
this.getBarData = this.getBarData.bind(this);
}
componentWillMount() {
this.getBarData(false); //first request
this.getBarData(true); //second request
}
async getBarData(earnings) {
let response = await axios.get(`/api/ranking/ranking_barchart?earnings=${earnings}`);
let {success, data, error} = response.data;
console.log(earnings);
console.log(data);
//The first request works fine. retrieves following
//[ { fill: true,
// backgroundColor: 'rgba(58, 79, 212, 0.4)',
// data: [ 11, 8, 8, 5, 5, 4, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] },
// { fill: true,
// backgroundColor: 'rgba(239, 49, 81, 0.4)',
// data: [ 0, 0, 0, 0, 10, 0, 15, 6, 10, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0 ] } ]
//Second request gives this
//[ { fill: true,
// backgroundColor: 'rgba(58, 79, 212, 0.4)',
// data: [ 11, 8, 8, 5, 5, 4, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] },
// { fill: true,
// backgroundColor: 'rgba(239, 49, 81, 0.4)',
// data: [ 11, 8, 8, 5, 5, 4, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] } ]
//Notice that this part is different from the first
if (!success) {
return this.setState({barDataError: error});
}
if (!earnings) {
return this.setState({barData: data});
}
this.setState({barDataEarnings: data});
}
render() {
const {classes} = this.props;
const {tableData, tableDataEarnings, barData, barDataEarnings} = this.state;
return (
<div className={classes.root}>
//I'm using this.state.barData and this.state.barDataEarnings here - I don't think this code has anything to do with the problem but if you need it I'll provide
</div>
);
}
}
export default withStyles(styles)(RankingsPage)
The component makes EXACTLY the same request except that the query value is different in the url. However, the data of the second index object is different to that of the first response.
Now the more interesting thing is the backend.
app.get('/api/ranking/ranking_barchart', authorize, async (req, res) => {
try{
let earnings = req.query.earnings === 'true';
// let sortBy = earnings ? {totalReceived: -1} : {totalDonated: -1};
let sortBy = {totalReceived: -1};
let topUsersResult =
await User.find({})
.sort(sortBy)
.limit(20)
.lean()
.exec();
let returnBody = {
labels: [],
datasets: []
};
let donationsMade = {
fill: true,
backgroundColor:'rgba(239, 49, 81, 0.4)',
data: []
};
let donationsReceived = {
fill: true,
backgroundColor:'rgba(58, 79, 212, 0.4)',
data: []
};
for(let i = 0; i< topUsersResult.length; i++) {
let curResult = topUsersResult[i];
returnBody.labels.push(curResult.username);
donationsMade.data.push(
curResult.totalDonated ? curResult.totalDonated : 0
);
donationsReceived.data.push(
curResult.totalReceived ? curResult.totalReceived : 0
);
}
returnBody.datasets.push(donationsReceived);
returnBody.datasets.push(donationsMade);
console.log(returnBody.datasets); //Print here is EXACTLY the same for both requests as expected
res.json(API_MSG.successMsg(returnBody));
}catch(e){
res.json(API_MSG.errorMsg(e, MSG_TYPES.FIND_ERROR, true));
}
});
I have it to NOT use the earnings query to test out with the EXACT same response. The code above is almost unnecessary because the console.log value is exactly the same as shown below. The console.log commented on the code above prints the following
//First Request
[ { fill: true,
backgroundColor: 'rgba(58, 79, 212, 0.4)',
data: [ 11, 8, 8, 5, 5, 4, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] },
{ fill: true,
backgroundColor: 'rgba(239, 49, 81, 0.4)',
data: [ 0, 0, 0, 0, 10, 0, 15, 6, 10, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0 ] } ]
//Second Request
[ { fill: true,
backgroundColor: 'rgba(58, 79, 212, 0.4)',
data: [ 11, 8, 8, 5, 5, 4, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] },
{ fill: true,
backgroundColor: 'rgba(239, 49, 81, 0.4)',
data: [ 0, 0, 0, 0, 10, 0, 15, 6, 10, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0 ] } ]
PLEASE tell me I'm not crazy. How is the EXACT same response that is being returned from the server some how being modified while it's being transported to the frontend???
I'm looking for advice on how I should/can configure Flotcharts using the Fillbetween and Threshold pluggins to create a chart that accomplishes the following:
Plot a line chart. (done)
Set some threshold values. (done)
Set and fill values that are outside of the threshold values. (not quite done)
Here's what I've accomplished so far,
https://jsfiddle.net/gstoa/utv4kvw2/
$(function() {
var values = {
'avgBottom': [
[1, -2],
[2, -2],
[3, -2],
[4, -2],
[5, -2]
],
'avgTop': [
[1, 3],
[2, 3],
[3, 3],
[4, 3],
[5, 3]
],
'values': [
[1, .5],
[2, -3],
[3, .8],
[4, 4.5],
[5, 6.6]
]
};
var dataset = [{
data: values['values'],
lines: {
show: true
},
color: "rgb(50,50,255)"
}, {
id: 'avgBottom',
data: values['avgBottom'],
lines: {
show: true,
lineWidth: 0,
fill: false
},
color: "rgb(50,50,255)"
}, {
id: 'values',
data: values['values'],
lines: {
show: true,
lineWidth: 0.5,
fill: 0.2,
shadowSize: 0
},
color: "rgb(50,50,255)",
fillBetween: 'avgBottom'
}, {
id: 'avgTop',
data: values['avgTop'],
lines: {
show: true,
lineWidth: 0,
fill: 0.2
},
color: "rgb(50,50,255)",
fillBetween: 'values'
}];
$.plot($("#placeholder"), dataset, {
xaxis: {
tickDecimals: 0
},
series: {
lines: {
show: true,
fill: true
},
points: {
show: false,
radius: 4
},
color: "#62CB31",
// threshold: {
// below: -2,
// color: "rgb(255,0,0)"
// }
},
yaxis: {
tickFormatter: function(v) {
return v;
}
}
});
$.plot($("#placeholder"), [d1, d2, d3]);
});
I'd like this line chart to look like the following:
Any advice is greatly appreciated.
To do this, I had to switch from the fillbetween to the fillbelow flot plugin. I then had to modify the source of the fillbelow plugin to look at a new fillColor property of the series (I've got a pull request to merge these changes back into the main branch).
All in all, your new data set looks like the code snippet below (this JSFiddle demonstrates how to get the chart to look like your example image).
var dataset = [{
id: 'topValues',
data: values['values'],
lines: {
show: true,
},
color: "rgb(50,50,255)",
fillBelowTo: 'avgTop',
fillBelowUseSeriesObjectFillColor: false,
fillColor: "#FF0000"
}, {
id: 'avgTop',
data: values['avgTop'],
lines: {
show: true,
lineWidth: 0,
fill: true
},
color: "rgb(50,50,255)"
}, {
id: 'bottomValues',
data: values['values'],
lines: {
show: true,
lineWidth: 0,
shadowSize: 0
},
color: "rgb(50,50,255)"
}, {
id: 'avgBottom',
data: values['avgBottom'],
lines: {
show: true,
lineWidth: 0,
fill: true,
},
fillBelowTo: 'bottomValues',
fillBelowUseSeriesObjectFillColor: false,
fillColor: "#FF0000",
color: "rgb(50,50,255)"
}];
The fillBelowTo property acts similarly to the fillBetween
property of the fillbetween plugin - it denotes to which series you'd
like to fill below to.
The fillBelowUseSeriesObjectFillColor
property (set to false) tells us to not use the lines.fillColor
color and instead use the fillColor value. If fillBelowUseSeriesObjectFillColor was true, the lines.fillColor color would be used (which in this case would be blue).
I'm trying to create a logstash pipeline that polls a ActiveMQ jolokia endpoint. I'm wanting to collect all the metrics for the queues on the broker. I have the following pipeline.
input {
http_poller {
urls => {
health_metrics => {
method => "get"
url => "http://localhost:8161/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=*"
headers => {
"Content-Type" => "application/json"
}
auth => {
user => "admin"
password => "admin"
}
}
}
request_timeout => 30
keepalive => false
interval => 5
codec => "json"
type => "activemq_broker_queue"
}
}
filter {
json_encode {
source => "value"
}
json {
source => "value"
}
mutate {
remove_field => ["request", "value", "timestamp"]
}
}
output {
elasticsearch {
hosts => "localhost"
# An index is created for each type of metrics inpout
index => "logstash-activmq"
document_type => "%{type}"
}
stdout {
codec => rubydebug
}
}
My jolokia response is in this format.
{
request: {
mbean: "org.apache.activemq:brokerName=localhost,destinationName=*,destinationType=Queue,type=Broker",
type: "read"
},
value: {
org.apache.activemq: brokerName=localhost,
destinationName=SEARCH,
destinationType=Queue,
type=Broker: {
ProducerFlowControl: true,
Options: "",
AlwaysRetroactive: false,
MemoryUsageByteCount: 0,
AverageBlockedTime: 0,
MemoryPercentUsage: 0,
CursorMemoryUsage: 0,
InFlightCount: 0,
Subscriptions: [],
CacheEnabled: true,
ForwardCount: 0,
DLQ: false,
StoreMessageSize: 0,
AverageEnqueueTime: 0,
Name: "SEARCH",
BlockedSends: 0,
TotalBlockedTime: 0,
MaxAuditDepth: 2048,
QueueSize: 0,
MaxPageSize: 200,
PrioritizedMessages: false,
MemoryUsagePortion: 1,
Paused: false,
EnqueueCount: 0,
MessageGroups: {
},
ConsumerCount: 0,
AverageMessageSize: 0,
CursorFull: false,
ExpiredCount: 0,
MaxProducersToAudit: 1024,
CursorPercentUsage: 0,
MinEnqueueTime: 0,
MemoryLimit: 668309914,
MinMessageSize: 0,
DispatchCount: 0,
MaxEnqueueTime: 0,
DequeueCount: 0,
BlockedProducerWarningInterval: 30000,
ProducerCount: 0,
MessageGroupType: "cached",
MaxMessageSize: 0,
UseCache: true,
SlowConsumerStrategy: null
},
org.apache.activemq: brokerName=localhost,
destinationName=weather,
destinationType=Queue,
type=Broker: {
ProducerFlowControl: true,
Options: "",
AlwaysRetroactive: false,
MemoryUsageByteCount: 0,
AverageBlockedTime: 0,
MemoryPercentUsage: 0,
CursorMemoryUsage: 0,
InFlightCount: 0,
Subscriptions: [],
CacheEnabled: true,
ForwardCount: 0,
DLQ: false,
StoreMessageSize: 0,
AverageEnqueueTime: 0,
Name: "weather",
BlockedSends: 0,
TotalBlockedTime: 0,
MaxAuditDepth: 2048,
QueueSize: 0,
MaxPageSize: 200,
PrioritizedMessages: false,
MemoryUsagePortion: 1,
Paused: false,
EnqueueCount: 0,
MessageGroups: {
},
ConsumerCount: 0,
AverageMessageSize: 0,
CursorFull: false,
ExpiredCount: 0,
MaxProducersToAudit: 1024,
CursorPercentUsage: 0,
MinEnqueueTime: 0,
MemoryLimit: 668309914,
MinMessageSize: 0,
DispatchCount: 0,
MaxEnqueueTime: 0,
DequeueCount: 0,
BlockedProducerWarningInterval: 30000,
ProducerCount: 0,
MessageGroupType: "cached",
MaxMessageSize: 0,
UseCache: true,
SlowConsumerStrategy: null
}
},
timestamp: 1453588727,
status: 200
}
I would like to be able to split the two queue destinations into two different documents and then save them to ES.
Currently I'm get an error about cannot contain '.'
Here my code
<div id="chart-revenue3" style="width:1100px; height:480px;" > </div>
var series = [{
data: [
[0, 100],
[1, 150],
[2, 125],
[3, 160],
[4, 95]
],
label: "Generes",
color:"#4598AE"
},
{
data: [
[0, 104],
[1, 157],
[2, 178],
[3, 145],
[4, 78]],
label: "Playlists",
color:"#8AA453"
}, {
data: [
[0, 55],
[1, 40],
[2, 60],
[3, 10],
[4, 20]
],
label: "Home",
color:"#A84745"
}, {
data: [
[0, 55],
[1, 40],
[2, 60],
[3, 10],
[4, 20]
],
label: "Search",
color:"#D98445"
}, {
data: [
[0, 55],
[1, 40],
[2, 60],
[3, 10],
[4, 20]
],
label: "New and Hot",
color:"#71598E"
},
{
data: [
[0,150],
[1, 200],
[2, 250],
[3, 120],
[4, 90]
],
label: "# Venues",
points: { show: false },
lines: { show: true,fill: false},
yaxis: 2,
color:"#81A0C1"
}];
var options = {
xaxis: {
minTickSize: 1,
ticks: [[0,'Dafault'],[1,'Alternative'],[2,'Country'],[3,'Latin'],[4,'Rock']]
}, yaxes: [
{
},
{
position: "right" , min:0, max: 1200, tickSize: 200
}
],
series: {
bars: {
show: true,
barWidth: .3,
align: "center",fillColor: {
colors: [{ opacity: 1 }, { opacity: 1 } ]
}
},
stack: true,
shadowSize:1
},
legend: { show: true, container: '#chart-revenue3-table' }
};
$.plot("#chart-revenue3", series, options);
so if i run this code am getting some extra color on bar chart..please give any idea
Ok, now I understand what you are trying to do. What you are missing is that you need to tell flot not to plot the # Venues series as a bar:
{
data: [
[0, 150],
[1, 200],
[2, 250],
[3, 120],
[4, 90]
],
label: "# Venues",
points: {
show: false
},
lines: {
show: true,
fill: false
},
yaxis: 2,
bars: {
show: false // <-- this is the bit you were missing
},
color: "#81A0C1"
}
http://jsfiddle.net/BrEJm/6/
The reason you need to do this is because in your options you set:
series: {
bars: {
show: true,
//...
}
}
And the way flot works is that it will merge those default set of series options with whatever explicit options you set for each series. So, even if you don't specify, all your series inherit bars.show = true.