sencha touch n3dv charts - charts

I've added a nvd3 chart to my sencha touch app.
Apparently though the size of the box where the chart will be inserted is undefined at the time the chart is created. This turns out in a graph with standard dimensions (960x350 approx), way too large!
How can I modify the widht and height of the chart? The visual error I get is that the chart has a larger width, the component containing it are smaller and the chart is not completely
visible (it's like it misses a resize effect to adapt its size to the containing box).
My code, which is inside a sencha component goes like this:
nv.addGraph(Ext.bind(function(){
var chart = nv.models.discreteBarChart()
.x(function(d) { return d.label; })
.y(function(d) { return d.value; })
.staggerLabels(true)
.tooltips(false)
.showValues(true);
var w = 550;
var h = 280;
var svg = d3.select(this.innerElement.dom).append('svg');
// setting axis property doesn't work:
var x = d3.scale.ordinal()
.domain(d3.range(10))
.rangeRoundBands([0, w], 1);
chart.xAxis
.tickFormat(d3.format(',f'));
chart.xAxis.scale(x);
chart.yAxis
.tickFormat(d3.format(',f'));
//setting svg properties doesn't work:
svg.attr("width", w)
.attr("height", h);
svg.datum(this.getChartData()).transition().duration(500).call(chart);
//if I comment this, nothing changes, what is this method for?
nv.utils.windowResize(chart.update);

Related

ChartJS: Custom tooltip always displaying

Im using ChartJS to create a graph on my website.
Im trying to create a custom tooltip. According to the documentation, this should be easy:
var myPieChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
tooltips: {
custom: function(tooltip) {
// tooltip will be false if tooltip is not visible or should be hidden
if (!tooltip) {
return;
}
}
}
}
});
My problem is that the tooptip is never false and because of this my custom tooltip is always displayed.
Please see this JSFiddle (line 42 is never executed)
Question: Is it a bug that tooltip is never false, or am I missing something?
The custom tooltip option is used for when you want to create/style your own tooltip using HTLM/CSS outside of the scope of the canvas (and not use the built in tooltips at all).
In order to do this, you must define a place outside of your canvas to contain your tooltip (e.g. a div) and then use that container within your tooltips.custom function.
Here is an example where I used a custom tooltip to display the hovered pie chart section percentage in the middle of the chart. In this example I'm generating my tooltip inside a div with id "chartjs-tooltip". Notice how I interact with this div in my tooltips.custom function to position and change the value.
Also, the correct way to check if the tooltip should be hidden is to check it's opacity. The tooltip object will always exist, but when it should not be visible, the opacity is set to 0.
Chart.defaults.global.tooltips.custom = function(tooltip) {
// Tooltip Element
var tooltipEl = document.getElementById('chartjs-tooltip');
// Hide if no tooltip
if (tooltip.opacity === 0) {
tooltipEl.style.opacity = 0;
return;
}
// Set Text
if (tooltip.body) {
var total = 0;
// get the value of the datapoint
var value = this._data.datasets[tooltip.dataPoints[0].datasetIndex].data[tooltip.dataPoints[0].index].toLocaleString();
// calculate value of all datapoints
this._data.datasets[tooltip.dataPoints[0].datasetIndex].data.forEach(function(e) {
total += e;
});
// calculate percentage and set tooltip value
tooltipEl.innerHTML = '<h1>' + (value / total * 100) + '%</h1>';
}
// calculate position of tooltip
var centerX = (this._chartInstance.chartArea.left + this._chartInstance.chartArea.right) / 2;
var centerY = ((this._chartInstance.chartArea.top + this._chartInstance.chartArea.bottom) / 2);
// Display, position, and set styles for font
tooltipEl.style.opacity = 1;
tooltipEl.style.left = centerX + 'px';
tooltipEl.style.top = centerY + 'px';
tooltipEl.style.fontFamily = tooltip._fontFamily;
tooltipEl.style.fontSize = tooltip.fontSize;
tooltipEl.style.fontStyle = tooltip._fontStyle;
tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};
Here is the full codepen example.
I hope that helps clear things up!

References in axis using chart.js (or another library)

Im trying to make a graph like this:
https://www.google.com/finance?q=BCBA:PAMP
I have a line chart in chart.js, now I want to add labels (like the letters A, B, C) for certain dates.
Can't find a doc/example to start from. Any idea?
If its more simple to do with another library a recommendation is more than welcome.
Thanks!
Unfortunately, there is no native support in chart.js for what you are wanting. However, you can certainly add this capability using the plugin interface. This requires that you implement your own logic to draw the canvas pixels at the locations that you want them. It might sound challenging, but its easier than it sounds.
Here is an example plugin that will add a value above specific points in the chart (based upon configuration).
Chart.plugins.register({
afterDraw: function(chartInstance) {
if (chartInstance.config.options.showDatapoints || chartInstance.config.options.showDatapoints.display) {
var showOnly = chartInstance.config.options.showDatapoints.showOnly || [];
var helpers = Chart.helpers;
var ctx = chartInstance.chart.ctx;
var fontColor = helpers.getValueOrDefault(chartInstance.config.options.showDatapoints.fontColor, chartInstance.config.options.defaultFontColor);
// render the value of the chart above the bar
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize + 5, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
ctx.fillStyle = fontColor;
chartInstance.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
if (showOnly.includes(dataset.data[i])) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
var scaleMax = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
var yPos = (scaleMax - model.y) / scaleMax >= 0.93 ? model.y + 20 : model.y - 5;
ctx.fillText(dataset.data[i], model.x, yPos);
}
}
});
}
}
});
It allows you to configure which points you want to annotate using this new configuration. The showOnly option contains the points that you want to label.
options: {
showDatapoints: {
display: true,
showOnly: [3, 10, 9]
},
}
Obviously, this only adds the datapoint value at the specified points, but you can just change the plugin to paint whatever you want to show instead. Simply replace ctx.fillText(dataset.data[i], model.x, yPos) with different code to render something different on the canvas.
Here is a codepen example to show you want it looks like.

Display values outside of pie chart in chartjs

When I hover on pie chart, the values are displayed in tooltip. However, I want to display values outside of pie chart. I want to make chart like this image:
How to do this?
I was able to get something similar working using chart.js v2.3.0 using both the plugin API and extending chart types API. You should be able to take this as a starting point and tweak it to your needs.
Here is how it looks after being rendered.
Note, this requires digging deep into chart.js internals and could break if they change the way tooltips are positioned or rendered in the future. I also added a new configuration option called showAllTooltips to enable selectively using the plugin on certain charts. This should work for all chart types, but I am currently only using it for pie, doughnut, bar, and line charts so far.
With that said, here is a working solution for the image above.
Chart.plugins.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create a namespace to persist plugin state (which unfortunately we have to do)
if (!chart.showAllTooltipsPlugin) {
chart.showAllTooltipsPlugin = {};
}
// turn off normal tooltips in case it was also enabled (which is the global default)
chart.options.tooltips.enabled = false;
// we can't use the chart tooltip because there is only one tooltip per chart which gets
// re-positioned via animation steps.....so let's create a place to hold our tooltips
chart.showAllTooltipsPlugin.tooltipsCollection = [];
// create a tooltip for each plot on the chart
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
// but only create one for pie and doughnut charts if the plot is large enough to even see
if (!_.contains(['doughnut', 'pie'], sector._chart.config.type) || sector._model.circumference > 0.1) {
var tooltip;
// create a new tooltip based upon configuration
if (chart.config.options.showAllTooltips.extendOut) {
// this tooltip reverses the location of the carets from the default
tooltip = new Chart.TooltipReversed({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart);
} else {
tooltip = new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart);
}
// might as well initialize this now...it would be a waste to do it once we are looping over our tooltips
tooltip.initialize();
// save the tooltips so they can be rendered later
chart.showAllTooltipsPlugin.tooltipsCollection.push(tooltip);
}
});
});
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we want to wait until everything on the chart has been rendered before showing the
// tooltips for the first time...otherwise it looks weird
if (!chart.showAllTooltipsPlugin.initialRenderComplete) {
// still animating until easing === 1
if (easing !== 1) {
return;
}
// animation is complete, let's remember that fact
chart.showAllTooltipsPlugin.initialRenderComplete = true;
}
// at this point the chart has been fully rendered for the first time so start rendering tooltips
Chart.helpers.each(chart.showAllTooltipsPlugin.tooltipsCollection, function (tooltip) {
// create a namespace to persist plugin state within this tooltip (which unfortunately we have to do)
if (!tooltip.showAllTooltipsPlugin) {
tooltip.showAllTooltipsPlugin = {};
}
// re-enable this tooltip otherise it won't be drawn (remember we disabled all tooltips in beforeRender)
tooltip._options.enabled = true;
// perform standard tooltip setup (which determines it's alignment and x, y coordinates)
tooltip.update(); // determines alignment/position and stores in _view
tooltip.pivot(); // we don't actually need this since we are not animating tooltips, but let's be consistent
tooltip.transition(easing).draw(); // render and animate the tooltip
// disable this tooltip in case something else tries to do something with it later
tooltip._options.enabled = false;
});
}
},
});
// A 'reversed' tooltip places the caret on the opposite side from the current default.
// In order to do this we just need to change the 'alignment' logic
Chart.TooltipReversed = Chart.Tooltip.extend({
// Note: tooltipSize is the size of the box (not including the caret)
determineAlignment: function(tooltipSize) {
var me = this;
var model = me._model;
var chart = me._chart;
var chartArea = me._chartInstance.chartArea;
// set caret position to top or bottom if tooltip y position will extend outsite the chart top/bottom
if (model.y < tooltipSize.height) {
model.yAlign = 'top';
} else if (model.y > (chart.height - tooltipSize.height)) {
model.yAlign = 'bottom';
}
var leftAlign, rightAlign; // functions to determine left, right alignment
var overflowLeft, overflowRight; // functions to determine if left/right alignment causes tooltip to go outside chart
var yAlign; // function to get the y alignment if the tooltip goes outside of the left or right edges
var midX = (chartArea.left + chartArea.right) / 2;
var midY = (chartArea.top + chartArea.bottom) / 2;
if (model.yAlign === 'center') {
leftAlign = function(x) {
return x >= midX;
};
rightAlign = function(x) {
return x < midX;
};
} else {
leftAlign = function(x) {
return x <= (tooltipSize.width / 2);
};
rightAlign = function(x) {
return x >= (chart.width - (tooltipSize.width / 2));
};
}
overflowLeft = function(x) {
return x - tooltipSize.width < 0;
};
overflowRight = function(x) {
return x + tooltipSize.width > chart.width;
};
yAlign = function(y) {
return y <= midY ? 'bottom' : 'top';
};
if (leftAlign(model.x)) {
model.xAlign = 'left';
// Is tooltip too wide and goes over the right side of the chart.?
if (overflowLeft(model.x)) {
model.xAlign = 'center';
model.yAlign = yAlign(model.y);
}
} else if (rightAlign(model.x)) {
model.xAlign = 'right';
// Is tooltip too wide and goes outside left edge of canvas?
if (overflowRight(model.x)) {
model.xAlign = 'center';
model.yAlign = yAlign(model.y);
}
}
}
});

android-graphview shows wrong graphs with setNumVerticalLabels

i test the android-graphview library and i find this behavior:
I use the latest GraphViewDemos and the first SimpleGraph example. It shows a linegraph with the correct data. (The y-axis values are 1,2,3)
GraphViewSeries exampleSeries = new GraphViewSeries(new GraphViewData[] {
new GraphViewData(1, 2.0d)
, new GraphViewData(2, 1.5d)
, new GraphViewData(2.5, 3.0d) // another frequency
, new GraphViewData(3, 2.5d)
, new GraphViewData(4, 1.0d)
, new GraphViewData(5, 3.0d)
});
The max value is three (Sorry i can't post an image) and all other coordinates are correct.
If i add these lines
graphView.getGraphViewStyle().setNumVerticalLabels(5);
graphView.setVerticalLabels( new String[]{"4","3","2","1","0"});
before
LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
layout.addView(graphView);
in the code to change the y-axis, i get a graph where the max-value is not still three, it's four. And all the other coordinates are wrong in the y-values.
Why does the complete graph change and not only the y-axis?
with the line:
graphView.setVerticalLabels( new String[]{"4","3","2","1","0"});
you set static labels to the graph. So the vertical labels (y-values) have no link to the data anymore.
This line is for dynamic labels. You can modify the count of the labels that will be generated.
graphView.getGraphViewStyle().setNumVerticalLabels(5);
But you are using static labels, so the line doesn't make sense.
http://android-graphview.org/
Visit this page and scroll to the Custom Label Formatter part of the tutorial.
GraphView graphView = new LineGraphView(this, "example");
graphView.setCustomLabelFormatter(new CustomLabelFormatter() {
#Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
if (value < 5) {
return "small";
} else if (value < 15) {
return "middle";
} else {
return "big";
}
}
return null; // let graphview generate Y-axis label for us
}
});
Basically you will have to map the actual y value with the static Vertical Label you have provided

copy chart control to new form

Is there a way to copy a chart control to a new form?
I have a Windows Form with a chart control on it, but the form is not allowed to be resizable. For that reason I have a button "Zoom" that opens the chart in a new form that is resizable. I have set a lot of chart properties in the "original" chart (axis color, axis intervalls etc.) and would like to just reuse this properties. I tried to call the constructor of the new form with the chart as parameter, but that didn't work.
public ZoomChartSeriesForm(Chart myChart)
My main problem is, that I allow zooming inside of the chart and that crashes, when I just copy the chart.
Here is the code of my "original chart" (example):
System.Drawing.Color color = System.Drawing.Color.Red;
//plot new doublelist
var series = new Series
{
Name = "Series2",
Color = color,
ChartType = SeriesChartType.Line,
ChartArea = "ChartArea1",
IsXValueIndexed = true,
};
this.chart1.Series.Add(series);
List<double> doubleList = new List<double>();
doubleList.Add(1.0);
doubleList.Add(5.0);
doubleList.Add(3.0);
doubleList.Add(1.0);
doubleList.Add(4.0);
series.Points.DataBindY(doubleList);
var chartArea = chart1.ChartAreas["ChartArea1"];
LabelStyle ls = new LabelStyle();
ls.ForeColor = color;
Axis a = chartArea.AxisY;
a.TitleForeColor = color; //color of axis title
a.MajorTickMark.LineColor = color; //color of ticks
a.LabelStyle = ls; //color of tick labels
chartArea.Visible = true;
chartArea.AxisY.Title = "TEST";
chartArea.RecalculateAxesScale();
chartArea.AxisX.Minimum = 1;
chartArea.AxisX.Maximum = doubleList.Count;
// Set automatic scrolling
chartArea.CursorX.AutoScroll = true;
chartArea.CursorY.AutoScroll = true;
// Allow user to select area for zooming
chartArea.CursorX.IsUserEnabled = true;
chartArea.CursorX.IsUserSelectionEnabled = true;
chartArea.CursorY.IsUserEnabled = true;
chartArea.CursorY.IsUserSelectionEnabled = true;
// Set automatic zooming
chartArea.AxisX.ScaleView.Zoomable = true;
chartArea.AxisY.ScaleView.Zoomable = true;
chartArea.AxisX.ScrollBar.IsPositionedInside = true;
chartArea.AxisY.ScrollBar.IsPositionedInside = true;
//reset zoom
chartArea.AxisX.ScaleView.ZoomReset();
chartArea.AxisY.ScaleView.ZoomReset();
chart1.Invalidate();
Copy as in deep copying the object?
I ran into this exact problem recently myself. Unfortunately, MS Chart has no method to clone their chart object and their class is not marked as serializable so you can't use the method suggested here.
If you want to do this the right way, you'll have to introduce a third party control such as Copyable or handle the reflection yourself, but this won't be easy.
A really nice workaround I found is to use the built-in serialization inside MS Chart control. The idea is to serialize the chart using memorystream, create a new instance of the chart and deserialize the chart.
private Chart CloneChart(Chart chart)
{
MemoryStream stream = new MemoryStream();
Chart clonedChart = chart;
clonedChart.Serializer.Save(stream);
clonedChart = new Chart();
clonedChart.Serializer.Load(stream);
return clonedChart;
}
Not exactly an efficient solution, but if performance isn't your priority, this works like a charm.