PieChart disappears on mouseout - chart.js

I am creating a very basic PieChart from the documentation on Chartjs.org. I think I am not doing anything fancy, or adding any extraneous libraries.
var data = [{
"value": 20,
"label": "Slice1"
}, {
"value": 10,
"label": "Slice2"
}];
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Pie(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Problem:
After the Pie Chart is rendered initially, if I mouseout over the chart, it disappears. It seems it is there as the tooltips appear when I mouseover, but not the chart/pie slices themselves.
This behavior was noticed in the latest Firefox and Chrome browsers.

So, per the Chart.js documentation, http://www.chartjs.org/docs/#doughnut-pie-chart-data-structure
For a pie chart, you must pass in an array of objects with a value and an optional color property
It turns out the color property is not so optional after all. Sure, the chart will render fine (as in all black pie slices, divided by white segment stroke color, pretty bad looking by default) with no Javascript errors. But, when you mousemove and mouseout of the pie, the colors magically change to white (with the same white segment stroke color), rendering the whole pie chart invisible against a white background, with only the tooltips showing on mousemove, mouseout.
The documentation of Chart.js should either make a note of this behavior, or make color a mandatory property or add good default colors, that don't change magically with mouse events.
But till then, users should assume the color property is mandatory to prevent headaches.
This is significant, as many developers will want to massage the data JSON returned from server to add UI related info, to keep the server side free of any UI logic.

Related

Chart.js x-axis label duplicating on hover

I'm working with Chart.js version 2.8 so not sure if it is in the version or if it is a common issue.
My chart loads fine at first but then my page refreshes and the duplicates can be seen when I hover on any of my charts(there are 4).
The duplicate looks like this:
!https://postimg.cc/3db6xFTz
I'm not sure what to try or where to start looking at what causes this. I've tried searching for similar cases but no one seems to have this issue. Any advice would be greatly appreciated.
Right, well I found the problem and the solution.
The root of the issue came about when my page refreshed and the chart would resize. I then tried the Chart.defaults.global.maintainAspectRatio= false;command which worked but duplicated the X-axis tick labels.
The problem: These two commands cannot work together. It causes the duplication on hover.
Chart.defaults.global.responsive = true;
Chart.defaults.global.maintainAspectRatio= false;
The solution: found in the chartjs.org documentation.
Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (example):
<div class="chart-container" style="position: relative; height:40vh; width:80vw">
<canvas id="chart"></canvas>
</div>
Note that in order for the above code to correctly resize the chart height, the maintainAspectRatio option must also be set to false.
I added the div's to encase my canvas, changed the sizing and this fixed my problem :)

can't set ChartJS canvas width

I can not get ChartJS to restrict itself to 200px. It takes the entire width of the browser. What am I missing.
I am using the following CDN
<div id="pnlChart" style="height:200px" >
<canvas id="myChart" width="400" height="200" class="chart" ></canvas>
</div>
my data that is being returned from the server appears to be well formed and drawing the chart correctly. It does not have the width/height in it. (I have pulled this from Chrome's dev tools.
{"type":"line","labels":[0,2,6,7,8,9,10,11,12,13,14,1,3,4,5,15,16,17,18,19,20,21,22,23],"datasets":[{"label":"Data","data":[2,1,8,36,119,179,214,165,87,173,220,0,0,0,0,0,0,0,0,0,0,0,0,0]}]}
You should be able to disable this container-width filling behaviour by telling Chart.js not to use responsive mode. Try passing this into the global configuration of the chart (the highest level of options):
options: {
responsive: false
}
See the Chart.js documentation for an example of how this fits into the full definition of a chart.
If that does not work for some reason then you could instead limit the width of the div element which contains the canvas on which your graph is drawn. Based on your example you could add this to your CSS:
div#pnlChart {width: 200px}
Even if you can get one of these methods to work, ideally you don't want to be specifying fixed widths for items these days because it makes it harder for pages to display well on the myriad of device screens which are in use now.
It's much better to develop a responsive layout for your site which will adjust to suit any screen width, from small smartphones to large desktop monitors. Search online for guides about "responsive design" for articles about this subject.

Color Themes in Google Charts

I am pretty familiar with Google Charts but was never able to find one thing. You can change the colors of your columns or bars or pie pieces or whatever in a couple of ways but essentially it comes down to something like this:
chart.draw(data, {
width: 400,
height: 240,
title: 'Toppings I Like On My Pizza',
colors: ['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6'],
is3D: true
});
Does anyone know how I can apply a "color theme"? Meaning, make the chart all bluish, or reddish or orangish. The hard coded color values work OK if you have a fixed data set but I am working on dynamic data sets. Sometimes I will have 3 series and sometimes 15, and I would like a way to set a chart color style/theme.

Chart.js Pie Chart: How to set background image for segment

I'm using Chart.js to create a pie chart (see below). Instead of the colors in each pie segment, I would like to use a background image.
Could you give me a pointer on how I could do this?
Thanks!
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
}
];
var myPieChart = new Chart(ctx[0]).Pie(data,options);
Subclass Pie, rewrite the initializer and addData - in the initializer re-define draw, adding one line:
if(this.bg_img)ctx.fillStyle=ctx.createPattern(this.bg_img,"repeat");
, right after it says:
ctx.fillStyle = this.fillColor;
(copy Pie's draw, add that line - or just copy my AltPie subclass from the bottom of the attached fiddle) This could be different for later versions but that's how Chart.js 1.01 is.
Also in your Pie subclass you will add a property (for example call it bg_img) for sending the background image through. To do this there is a one-line addition, so re-define addData inside AltPie and add the property inside the splice line:
bg_img : segment.bg_img,
for example somewhere around the line
fillColor : segment.color,
That's most of it - other than that you will load and then attach the images to the data you're making the chart with. To load them you can use
....img=new Image();...img.src=...and - img.onload=function()(..recurse-load-next,
with a recursing callback similar to solution #2 from this page:
stackoverflow.com/questions/4960111/image-as-a-background-to-a-drawn-shape
I think you would need to make sure the images are done loading before attaching them to the data and sending them through to the Chart.js renderer, hence the recursion pattern to load them one by one before attaching them to the chart data and then creating the new AltPie chart.
The end result is that your images will show up in the pie pieces backgrounds or you can still use a color background if there's no image. It changes the html5 canvas ink pattern
(ctx.fillStyle=ctx.createPattern(this.bg_img,"repeat"))
to be the image you attached to the chart data, also taken from solution #2 from the same page: stackoverflow.com/questions/4960111/image-as-a-background-to-a-drawn-shape.
For the complete working example see attached fiddle https://jsfiddle.net/arlon_arriola/pkwftkp2/
The dependencies for loading the page are Chart.js file (v1.01?) (which is just copy/pasted into the fiddle at the top making the code look extremely long but the relvant code is at the very bottom), and the images inside your ./imgs/patterns/ folder, and the reference to some hosted jquery (1.9?). (and a body tag)
I am sure you could get image rollovers too, just attach two images to the data, figure out where it re-draws for hovering and modify it the same way as the regular draw.

Modifying the dimensions of a pie chart (Google Chart Tools)

Short version - I want to modify the width/height of a google.visualization.PieChart object after construction, but I can't find any documentation pointing out how it's done.
Context - I'm building a visualization that overlays a bunch of data on a Google Map. At certain lat/long coordinates I want to render a pie chart marker detailing certain statistics that are relevant to that place.
To avoid cluttering up the screen, I want to vary the dimensions of the pie chart markers based on the current zoom level. This requires me to either re-render all markers that are currently visible or, preferably, change the width/height attributes of all markers.
I currently use the following settings to render my charts:
legend: {position: "none"},
width: 200,
height: 200,
backgroundColor: "transparent",
pieSliceText: "none",
colors: ["#C10001", "#F79647", "#92D051", "#558ED5", "#7F7F7F"],
tooltip: {textStyle: {fontSize: 14}}
Is there a way to alter the dimensions of the chart after it's created?
I do not think there's something in the API; nevertheless with a tiny bit of Javascript you should be able to modify the attribute of the SVG tag containing the chart. One possible way is to add a viewBox attribute that will scale up or down the pie chart.
The only working solution I have so far is to redraw the entire chart with changed width/height settings. This snippet uses jQuery.
for (var i = 0; i < dataPoints.length; ++i) {
var drawingOptions = $.extend({}, defaultDrawOptions);
drawingOptions.width = defaultDrawOptions.width*(currentZoom/defaultZoom);
drawingOptions.height = defaultDrawOptions.height*(currentZoom/defaultZoom);
dataPoints[i].chart.draw(dataPoints[i].dataSource, drawingOptions);
}
As you can see, this half-baked solution is rather clumsy and might needlessly deteriorate performance.