I am trying to use d3-based charting library xChart to create a graph module in my webapp. I am just using the example data provided by the xChart documentation, and I get this error every time I try to create the chart:
Uncaught TypeError: Cannot read property 'getPropertyValue' of null
The error is on line 666 (lol) of d3.js in the getComputedStyle method.
if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name);
My JavaScript is as follows:
var data = {
xScale: "ordinal",
yScale: "linear",
main: [
{
className: ".pizza",
data: [
{
x: "Pepperoni",
y: 4
}, {
x: "Cheese",
y: 8
}
]
}, {
className: ".pizza",
data: [
{
x: "Pepperoni",
y: 6
}, {
x: "Cheese",
y: 5
}
]
}
]
};
var myChart = new xChart('bar', data, '#graph-figure');
And my HTML is
<figure id="graph-figure"></figure>
Can anyone help me out with this?
You are most likely executing your javascript before the dom is ready. You can either wrap your javascript in a window.onload function...
window.onload = function(){
// your code here
}
Or include your <script> or inline code right before your closing </body> tag.
Related
I'm making a website with one graph that use ChartJS library. This chart display, on the website, all of the data available as default.
My goal is to let the visitors to choose a different number of data of the graph. So, I did one button at the top of the chart which, when a visitor click on it, must change the number of data displayed.
The problem is that ChartJS use a JSON object and I not succeed configure different behaviors in it.
...
datasets: [
{
label: "Exemple",
data: [
{ x: "Day1", y: 0 },
{ x: "Day2", y: 1 },
{ x: "Day3", y: 2 },
{ x: "Day4", y: 3 },
{ x: "Day5", y: 4 },
....
],
...
I tried to put an event on it, like :
data: mybutton.addEventListener("click", () => {
[{x: "Day1", y: 0}]
},
A function, like :
data: myFunction(),
Even a variable with function into, like :
const myData = () => {
// function
}
data: myData,
Or an If else.
Nothing worked... Do you any idea ?
I found the solution by myself.
I put the JSON object in a function, put an AddEventListener("click", function()), targeted the part of the JSON to modify and added an update() at the end.
function chartFunction() {
....
// data before
datasets: [
{
label: "Exemple",
data: [
{ x: "Day1", y: 0 },
.....
button.addEventListener("click", () => {
(myChart.data.datasets[0].data = [...]).myChart.update();
});
};
chartFunction();
I am trying to make a very simple chart with negative values and centered labels,
I have tried everything and this stupid thing won't work, I found some examples, dint work either, if anyone here build a chart like this and could share the code, or help me with , i will relay REALLY appreciate it. please,
I am using canvasJS.
I need something like this:
*sorry for bad English please help thank you.
this is my basic chart, (if needed):
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
axisY:{
gridThickness: 0,
},
axisX:{
title: "",
tickLength: 0,
margin:0,
lineThickness:0,
valueFormatString:" ",
},
data: [
{
type: "bar",
dataPoints: [
{ y: -3.5 },
{ y: -3.89 },
{ y: 4.5 },
{ y: 5 },
{ y: 4 },
]
}
]
});
chart.render();
}
My ultimate goal is to use information from my database to create a line graph using my MVC application. So far I have managed to gather this data using a view model and LINQ queries in my controller and I have made sure the data is accurate by running a test in the view. However, I'm having a hard time figuring out how to include it in my JavaScript file. In my controller I have a function
private DataBase db = new DataBase();
public ActionResult GetInfo() {
var model = new UserViewModel();
model.val1=db.table.Where(n=>n.UserID==curUser).Select(n=>n.SomeData).ToArray();
model.val2=db.table.Where(n=>n.UserID==curUser).Select(n=>n.MoreData).ToArray();
model.dictionary = the stuff from above;
And then in my JavaScript file I'm using Chart.Js to graph a chart. So far it just has fake data to make sure everything was linked up correctly but it looks like this:
jQuery(document).ready(function() {
var chart=new CanvasJS.Chart("moodgraph",{
animationEnabled: false,
theme: "light2",
title: {
text: "Simple Line Chart"
},
axisY: {
includeZero: false
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: [
{ x: 1,y: 450 },
{ y: 414 },
{ y: 520,indexLabel: "\u2191 highest",markerColor: "red",markerType: "triangle" },
{ y: 460 },
{ y: 450 },
{ y: 500 },
{ y: 480 },
{ y: 480 },
{ y: 410,indexLabel: "\u2193 lowest",markerColor: "DarkSlateGrey",markerType: "cross" },
{ y: 500 },
{ y: 480 },
{ y: 510 }
]
}]
});
chart.render();
});
That graph does appear in my view so I know all that is working fine. What I've been struggling with is figuring out how to get that dataPoints to populate with the dictionary values that I grabbed in my controller... So far I tried using
var model=#Model.Dictionary
to access the information but that threw an error. And then I've struggled with trying to return an object in the controller but that messes with code that I can't touch as someone else wrote it for this project. I know I'm missing one simple piece but my Google searches don't show me how to do this in the strict parameters I'm stuck with in this project.
How do I access the view model data in my separate JavaScript file?
you can use this :
1 - In your controller :
*
*
ViewBag.Dico = model.dictionary;
return View("chartPage");
2 - in your chartPage.cshtml (or declare your variable globally 'Layout.cshtml'):
<script>
var myPoints= #Html.Raw(Json.Encode(ViewBag.Dico));
</script>
3 - in ChartJs:
jQuery(document).ready(function() {
var chart=new CanvasJS.Chart("moodgraph",{
*
*
*
},
data: [{
type: "line",
indexLabelFontSize: 16,
dataPoints: (typeof(myPoints) != "undefined" ? myPoints: [])
}]
});
chart.render();
});
using Chart.JS library you can make dynamic charts from the database data by following the next steps
Model:
suppose you have model for graph data as following:
public class JsResultChart
{
public string Name { get; set; }
public double Value { get; set; }
}
Controller:
return your data from the controller (using model, viewbag..etc) as list
var JsResultChart= new List<JsResultChart>
{
new JsResultChart{ Name ="first", Value = 100 }, //data will be fetched from db
new JsResultChart{ Name ="second", Value = 200 },
};
Model.JsResultChart = JsResultChart;
View:
add something like this:
<div class="row">
<div class="col-md-12">
<input type="hidden" id="Lables" name="Lables" value="#Json.Encode(Model.ChartData.Select(x => x.Name).ToList())" />
<input type="hidden" id="Values" name="Values" value="#Json.Encode(Model.ChartData.Select(x => x.Value).ToList())">
<canvas id="myChart" style="margin: 0 auto;" class="NotPrintable"></canvas>
<div id="ResultsDiv"></div>
</div>
</div>
javascript:
var Names = $("#Lavels").val();
var Numbers = $("#Values").val();
Names = JSON.parse(Names);
Numbers = JSON.parse(Numbers);
var data = {
labels: Names,
datasets: [{
fill: false,
data: Numbers,
label: "Value" //you can write(label: Names) rather than (label: "Value")
}]
};
var ctx = $("#myChart");
var barChart = new Chart(ctx, {
type: 'line',
data: data,
options: options //add your options
});
Currently I have a request to have a Bullet Chart with two targets (min and max).
To do it I am simply using a normal Bullet Chart with a Scatter series to draw the other target. I would like to wrap this behavior inside the bullet chart, so it would have something like the following options:
series: [{
data: [{
y: 275,
target: 250,
minTarget: 100
}]
},
And then, on the wrap, I would get this minTarget and make a scatter plot automatically. How can I do it?
Here's the fiddle I have so far: http://jsfiddle.net/gwkxd02p/
I do not think that render is a good method to add another series - anyway, you can try to do it like this:
Highcharts.wrap(Highcharts.seriesTypes.bullet.prototype, 'render', function(p) {
if (!this.hasRendered) {
const scatterData = this.points
.map(({ x, y, options }) => ({
x,
y: options.minTarget !== undefined ? options.minTarget : null
}))
if (scatterData.length) {
const scatter = this.chart.addSeries({
type: 'scatter',
data: scatterData,
marker: {
symbol: 'line',
lineWidth: 3,
radius: 8,
lineColor: '#000'
}
}, false)
scatter.translate()
scatter.render()
}
}
p.call(this)
})
And data for bullet:
series: [{
data: [{
y: 275,
target: 250,
minTarget: 100
}, {
y: 100,
target: 50
}, {
y: 500,
target: 600,
minTarget: 20
}]
live example: http://jsfiddle.net/n4p0ezzw/
I think that the better place is bullet's init method but in that method the points do not exist yet - so you would have to match the x values (if it is needed) on your own.
My suggestion is - do not wrap Highcharts if you don't have to. A better (simpler, safer, cleaner, easier to debug, it does not change Highcharts internal code) practice would be to wrap the Highcharts constructor in a function and parse the options inside it and then call the chart constructor with new options, like this:
function customBullet(container, options) {
const newOptions = {} // parse options, check for minTarget, etc. and create new options
return Highcharts.chart(container, newOptions)
}
I'm completely new to JSFiddle. I'm currently trying to get a scatter chart to show up but nothing is displaying. Can anyone point me in the right direction?
Here's the Fiddle: http://jsfiddle.net/roka545/qf8ejytt/
//Get context with jQuery - using jQuery's .get() method.
let canvas = <HTMLCanvasElement>document.getElementById("myChart");
let ctx = canvas.getContext("2d");
let xAxisMin: number = 4;
let xAxisMax: number = 7;
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
You need to add a link to the actual source such as:
https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.min.js
In the external resources, then press plus button.
See here:
http://jsfiddle.net/r7ahsn15/
Did you look at the console? It says:
And that's because:
Meaning that the link you provided was over http rather than https as jsfiddle. Browsers don't allow that kind of requests (http inside https sites) for security reasons.
Nevertheless, I'm searching for a working example and it seems that all the chart.js fiddles are having the same error:
https://jsfiddle.net/uc25erpc/
https://jsfiddle.net/achudars/NXPhL/
http://fiddle.jshell.net/leighking2/898kzyp7/