how to set max legend width - legend

I have right aligned legend and I need to give it max width 25% of whole chart container. I've tried set width to 25% but in case when my series name is short legend box still stays as 25% but should be equal to content width. So I am looking for maxWidth property if it exist. I am in styled mode. Here is the the code http://jsfiddle.net/sabira/xmcqjnvg/24/
Highcharts.chart('container', {
chart: {
styledMode: true,
},
legend: {
align: 'right',
layout: 'proximate',
},
series: [{
name: 'very long long long long long name',
data: [1, 4, 3, 5],
},
{
name: 'short',
data: [3, 5, 3, 1],
}]
});

The legend.maxWidth property doesn't exist. However, it can be achieved by checking legend width in the chart load event and update it when it is bigger than eg. '25%' of the chart width.
Code:
chart: {
styledMode: true,
events: {
load: function() {
var chart = this,
legend = chart.legend,
legendMaxWidth =
Highcharts.relativeLength(legend.options.maxWidth, 1) * chart.chartWidth;
if (legend.legendWidth > legendMaxWidth) {
legend.update({
width: legend.options.maxWidth
});
}
}
}
}
Demo:
https://jsfiddle.net/BlackLabel/fpwdtghk/
API reference:
https://api.highcharts.com/class-reference/Highcharts.Legend#update

For some one looking for an easier alternative to this just use itemWidth property of legend.
legend:{ itemWidth: 100 }
Updated Fiddle:
http://jsfiddle.net/3mvpbu1f/

Related

How to show informations in graphs using jsp and CanvasJS?

I need to draw graphs with my sql server data .
So I have my servlet that select all data I need and transform it to json , then I forward all data to my jsp.
what I want is to show information like names in my pie graph .
this is my servlet :
PreparedStatement ps = c.prepareStatement("select SUM(ChiffreAffaire)as CA,M500_NOM from V502_client where Annee=? and Mois=2 group by M500_NOM");
ps.setString(1, name);
ResultSet resultSet = ps.executeQuery();
while(resultSet.next()){
yVal = resultSet.getFloat("CA");
nom=resultSet.getString("M500_NOM");
map = new HashMap<Object,Object>(); map.put("x", nom);map.put("y",yVal); list.add(map);
dataPoints = gsonObj.toJson(list);
}
request.getSession().setAttribute("data", dataPoints);
RequestDispatcher rd = request.getRequestDispatcher("graph.jsp");
rd.forward(request, response);
and this is the script to show my graph :
<script type="text/javascript">
<% String shared1 = (String)request.getSession().getAttribute("data");%>
window.onload = function() {
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
title: {
text: "Représentation graphique"
},
data: [{
type: "pie", //change type to bar, line, area, pie, etc
showInLegend: "true",
startAngle: 40,
dataPoints: <%out.print(shared1);%>
}]
});
chart.render();
}
</script>
<div id="chartContainer" style="height:370px; width:600px;"></div>
The result of this is shown like :
I want to be like this :
Try to define legendText on your dataset and indicate, which property contains the label ('x' in your case).
data: [{
type: "pie",
showInLegend: true,
legendText: "{x}",
startAngle: 40,
dataPoints: <%out.print(shared1);%>
}]
Please note that every label (x property) should be different for a pie chart.

Specify the color for a Pie in Dojo Charting

I am using Dojo 1.9, using memoryStore and the store has 4 data elements, in addition to the key. For each of the 4 data elements, I need to plot a Pie-Chart. working fine but only issue is that I do not know how to specify the color.
The identifier could be one of the Following - Low, Moderate,High and Extreme.
I want to use the same colors for each identifier, in all the charts. Is it possible for me to specify a color based on the value of the identifier?
The code snippet is as shown below:
var store = new Observable(new Memory({
data: {
identifier: "accumulation",
items: theData
}
}));
theChart.setTheme(PrimaryColors)
.addPlot("default", {
type: Pie,
font: "normal normal 11pt Tahoma",
fontColor: "black",
labelOffset: -30,
radius: 80
}).addSeries("accumulation", new StoreSeries(store, { query: { } }, dataElement));
I'm possibly misunderstanding your question here (is the plot interacting directly with the store? StoreSeries?), but is the fill property what you're looking for?
// Assuming data is an array of rows retrieved from the store
for(var i etc...) {
// make chart
// ...
chart.addSeries("things", [
{ y: data[i]["low"], fill: "#55FF55", text: "Low" },
{ y: data[i]["mod"], fill: "#FFFF00", text: "Moderate" },
{ y: data[i]["high"], fill: "#FFAA00", text: "High" },
{ y: data[i]["extr"], fill: "#FF2200", text: "Extreme" }
]);
}
Update: When using a StoreSeries, the third argument (dataElement in your code) can also be a function. You can use the function to return an object (containing the properties above, such as fill) instead of just a value.
chart.addSeries("thingsFromStore", new StoreSeries(store, {}, function(i) {
return {
y : i[dataElement],
text: "Label for " + i.accumulation,
fill: getColorForAccumulation(i)
};
}));

JqPlot EnhancedLegendRenderer with Mouse events

I am using JqPlot to display some graph legends on the jqplotMouseEnter, and jqplotMouseLeave events.
Here is my code:
$('#FinancialsLineGraph').bind('jqplotMouseEnter', function(ev, seriesIndex, pointIndex, data) {
$('#FinancialsLineGraph .jqplot-table-legend').show();
});
$('#FinancialsLineGraph').bind('jqplotMouseLeave', function(ev, seriesIndex, pointIndex, data) {
$('#FinancialsLineGraph .jqplot-table-legend').hide();
});
With this above code, when the cursor is moved over the actual legend inside the graph, the legend 'flickers' and the user cannot use the EnhancedLegendRenderer to shown/hide the corresponding series in the plot.
How can I get this above feature working?
Thanks in advance.
EDIT
Here is my JS plot code.
var plotCogsLineGraph = $.jqplot('FinancialsLineGraph', [[30,31,34,40,45], [34,38,31,42,38]],
{
axes:
{
xaxis:
{
ticks: ['5','4','3','2','1']
},
yaxis:
{
label:'%',
pad: 1.05,
ticks: ['0','15','30','45','60']
}
},
width: 480, height: 270,
legend:{show:true, location: 's', placement: 'insideGrid', renderer: $.jqplot.EnhancedLegendRenderer},
seriesDefaults:
{
rendererOptions: {smooth: true}
},
series:[
{
lineWidth:1,
label:'COGS',
markerOptions: { size:1, style:'dimaond' }
},
{
lineWidth:1,
label:'Wages',
markerOptions: { size: 1, style:"dimaond" }
}
]
}
);
What's actually happening here is that the jqplotMouseLeave event is being raised when you enter the legend, causing it to not be displayed, which then raises the jqplotMouseEnter (when the legend is hidden, you all of a sudden enter the plot), causing it to be shown. Because of this cycle, you get the flickering.
Try changing your 'jqplotMouseLeave handler to this:
$('#FinancialsLineGraph).bind('jqplotMouseLeave', function(ev, seriesIndex, pointIndex, data) {
var top, right, bottom, left;
var legend = $('#FinancialsLineGraph .jqplot-table-legend');
top = legend.offset().top;
left = legend.offset().left;
bottom = top + legend.height();
right = left + legend.width();
if (!(ev.pageX >= left && ev.pageX <= right && ev.pageY >= top && ev.pageY <= bottom)) {
$('#chart1 .jqplot-table-legend').hide();
}
});
What this does is hide the legend only if the mouse cursor location is not contained within the legend's bounding box.

FullCalendar and Flot Resize Conflict

I've successfully integrated both a Flot line graph and an instance of FullCalendar into my site. They are both on separate pages (although the pages are loaded into a div via AJAX).
I've added the Flot Resize plugin and that works perfectly, re-sizing the line graph as expected. However, it seems to cause an error when resizing the calendar.
Even if I load the calendar page first, when I resize the window I get this error in the console (also, the calendar does not resize correctly):
TypeError: 'undefined' is not an object (evaluating 'r.w=o!==c?o:q.width()')
I was struggling to work out where the error was coming from, so I removed the link to the Flot Resize JS and tried again. Of course the line graph does not resize, but when resizing the calendar, it works correctly.
The div containers for the two elements have different names and the resize function is called from within the function to draw the line graph (as required).
I have tried moving the link to the Flot Resize plugin into different places (i.e. above/below the fullCalendar JS, into the template which holds the graph), but all to no avail.
Does anyone have any idea where the conflict might be and how I might solve it??
Thanks very much!
EDIT: It seems that the error is also triggered when loading the line graph (flot) page AFTER the fullcalendar page even without resizing the window.... Now I am very confused!
EDIT 2: The code which draws the line graph. The function is called on pageload and recieves the data from JSON pulled off the server. When the graph is loaded, I still get the error about shutdown() being undefined.
function plotLineGraph(theData){
var myData = theData['data'];
var myEvents = theData['events'];
var myDates = theData['dates'];
var events = new Array();
for (var i=0; i<myEvents.length; i++) {
events.push(
{
min: myEvents[i][0],
max: myEvents[i][1],
eventType: "Calendar Entry",
title: myEvents[i][2],
description: myEvents[i][3]
}
);
}
function showTooltip(x, y, contents) {
$('<div id="tooltip">' + contents + '</div>').css( {
position: 'absolute',
display: 'none',
top: y + 5,
left: x + 5,
border: '1px solid #fdd',
padding: '2px',
'background-color': 'black',
opacity: 0.80
}).appendTo("body").fadeIn(200);
}
var previousPoint = null;
$("#placeholder").bind("plothover", function (event, pos, item) {
$("#x").text(pos.x.toFixed(2));
$("#y").text(pos.y.toFixed(2));
if ($("#enableTooltip:checked").length == 0) {
if (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
if(item.series.label != null){
showTooltip(item.pageX, item.pageY,
item.series.label + " of " + y);
}
}
}
else {
$("#tooltip").remove();
previousPoint = null;
}
}
});
var d1 = [
myData[0], myData[1], myData[2], myData[3], myData[4],
myData[5], myData[6], myData[7], myData[8], myData[9],
myData[10], myData[11], myData[12], myData[13], myData[14],
myData[15], myData[16], myData[17], myData[18], myData[19],
myData[20], myData[21], myData[22], myData[23], myData[24],
myData[25], myData[26], myData[27], myData[28], myData[29]
];
var markings = [
{ color: '#FFBDC1', yaxis: { from: 0, to: 2 } },
{ color: '#F2E2C7', yaxis: { from: 2, to: 3.5 } },
{ color: '#B6F2B7', yaxis: { from: 3.5, to: 5 } }
];
$.plot($("#placeholder"), [
{label: "Average Daily Rating", data: d1, color: "black"}
], {
events: {
data: events,
},
series: {
lines: { show: true },
points: { show: true }
},
legend: { show: true, container: '#legend-holder' },
xaxis: {
ticks:[
myDates[0], myDates[1], myDates[2], myDates[3], myDates[4],
myDates[5], myDates[6], myDates[7], myDates[8], myDates[9],
myDates[10], myDates[11], myDates[12], myDates[13], myDates[14],
myDates[15], myDates[16], myDates[17], myDates[18], myDates[19],
myDates[20], myDates[21], myDates[22], myDates[23], myDates[24],
myDates[25], myDates[26], myDates[27], myDates[28], myDates[29]
],
},
yaxis: {
ticks: 5,
min: 0,
max: 5
},
grid: {
backgroundColor: { colors: ["#fff", "#eee"] },
hoverable: true,
clickable: true,
markings: markings
},
selection: {
color: 'white',
mode: 'x'
},
});
$('#placeholder').resize();
$('#placeholder').shutdown();
}
EDIT 3:
The calendar is called like this:
function showCalendar() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#fullcalendar').fullCalendar({
header: {
left: 'prev',
center: 'title',
right: 'next'
},
clickable: true,
firstDay: 1,
eventSources: [
{
url: '/populate-calendar/{{theProductUuid}}/',
color: 'black',
data: {
text: 'text'
}
}
],
eventClick: function(calEvent, jsEvent, view) {
var startDate = $.fullCalendar.formatDate(calEvent.start, 'yyyy-MM-dd');
var endDate = $.fullCalendar.formatDate(calEvent.end, 'yyyy-MM-dd');
var eventId = calEvent.uuid;
$('#modal-event-title').text(calEvent.title);
$('#edit-event-name').val(calEvent.title);
$('#edit-start-date').val(startDate);
$('#edit-end-date').val(endDate);
$('#edit-event-text').val(calEvent.text);
$('#edit-event-btn').attr('data-uuid', eventId);
$('#modal-edit-event').on('click', '#delete-btn', function(){
deleteCalendarEvent(eventId);
});
$('#modal-edit-event').modal();
},
});
}
The AJAX to load the page containing the flot chart:
function loadDetailedReports(uuid){
$('#product-content').fadeOut('slow', function(){
$('#product-content').empty();
$('#whole-product-sub-nav .active').removeClass('active');
$('#detailed-reports-content').load('/detailed-reports/' + uuid + '/', function(){
$('#detailed-reports-btn').addClass('active');
$('#detailed-reports-content').fadeIn('slow', function(){
if (authorized){
setLocationHash('loadDetailedReports&' + uuid);
getChartData(uuid);
} else {
setLocationHash('');
}
});
});
});
}
And the AJAX to load the page containing the calendar:
function loadCalendar(uuid){
$('#detailed-reports-content').empty().hide();
$('#product-content').fadeOut('slow', function(){
$('#whole-product-sub-nav .active').removeClass('active');
$('#product-content').load('/calendar/' + uuid + '/', function(){
$('#calendar-btn').addClass('active');
$('#product-content').fadeIn('slow', function(){
if (authorized){
setLocationHash('loadCalendar&' + uuid);
} else {
setLocationHash('');
}
showCalendar();
});
});
});
}
The calls to .resize and .shutdown are there because I was under the impression that they are necessary to achieve the resizing function and in response to your earlier comment regarding shutdown...... They're quite possibly n00b errors........?!?!
It looks like this is triggering on line 198 of jquery-resize:
data.w = w !== undefined ? w : elem.width();
This sounds like a race-condition stemming from the way you load different content into the same div. Flot binds the resize event to the chart div, and only un-binds it if the plot is destroyed cleanly.
EDIT: Looking at your code, my first suggestion would be to get rid of the resize and shutdown calls at the end of plotLineGraph. The resize plugin doesn't require any setup; it hooks into Flot to attach automatically to any new plot. So your call to resize is actually to jQuery's resize event trigger, which may be what's causing the error.
EDIT #2: I'm still not clear on your structure, but to generalize: anywhere that you might be getting rid of #placeholder (via emptying its parent or anything like that) you should first call shutdown on the plot object. If you aren't keeping a reference to it, you can do it like this: $("#placeholder").data("plot").shutdown(); but then have to account for the fact that it's undefined prior to the creation of your first plot.
If that still doesn't work, I'd need to see a live (simplified) example to make any further suggestions.

ExtJS How to add a click event to Pie Chart pieces

I have created a Pie chart using the Pie chart example in sencha ExtJS website , I wanted to add a click event to the each Pie slice so that i get handle to the contextual data on that slice. I was able to add a click listener to the Pie but not sure how to get the data on the slice.
Below is the ExtJS code.
Ext.onReady(function(){
var store = Ext.create('Ext.data.JsonStore', {
fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
data: [{
'name': 'January',
'data1': 10
}, {
'name': 'February',
'data1': 7
}, {
'name': 'March',
'data1': 5
}, {
'name': 'April',
'data1': 2
}, {
'name': 'May',
'data1': 27
}]
});
Ext.create('Ext.chart.Chart', {
renderTo: Ext.getBody(),
width: 800,
height: 600,
animate: true,
store: store,
theme: 'Base:gradients',
legend: { // Pie Chart Legend Position
position: 'right'
},
series: [{
type: 'pie',
field: 'data1',
showInLegend: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item){
//calculate and display percentage on hover
var total = 0;
store.each(function(rec){
total += rec.get('data1');
});
this.setTitle(storeItem.get('name') + ': ' + Math.round(storeItem.get('data1') / total * 100) + '%');
}
},
highlight: {
segment: {
margin: 5
}
},
label: {
field: 'name',
display: 'rotate',
contrast: true,
font: '18px Arial'
},
listeners: {//This Doesnt Work :(
itemclick: function(o){
alert('clicked at : ' + o);
}
}
}],
listeners: { //This Event handler works but I am not sure how to figure how which slice i have clicked ..................................
click: {
element: store, //bind to the underlying el property on the panel
fn: function(o, a){
alert('clicked' + o + a + this);
}
}
}
});
});
Kindly help.
Regards,
Lalit
Here is how you get data of the clicked slice. The series class supports listeners via the Observable syntax and they are:
itemmouseup When the user interacts with a marker.
itemmousedown When the user interacts with a marker.
itemmousemove When the user iteracts with a marker.
afterrender Will be triggered when the animation ends or when the series has been rendered completely.
I will make use of the itemmousedown event to capture the clicked slice. Here is my listener method:
series: [{
.
.
.
listeners:{
itemmousedown : function(obj) {
alert(obj.storeItem.data['name'] + ' &' + obj.storeItem.data['data1']);
}
}
.
}]
Note that I have placed my listener inside the series and not the chart! Now, the obj variable holds lot of information. For each series, the property to get data will differ. So, you will have to carefully inspect the object using firebug or some other developer tool.
Now, in case of Piecharts, you can get the slice information by using the obj:
obj.storeItem.data['your-series-variable-name']
Here is the obj from firebug..
I'm using a more selective approach, because I needed to add some custom logic in order to implement drag-and-drop for our charts. So after the chart definition I just add the following:
// Add drag-and-drop listeners to the sprites
var surface = chart.surface;
var items = surface.items.items;
for (var i = 0, ln = items.length; i < ln; i++) {
var sprite = items[i];
if (sprite.type != "circle") { continue; } // only add listeners to circles
// Additional funky checks for the draggable sprites
sprite.on("mousedown", onSpriteMouseDown, sprite); // mouse down ONLY for sprites
}
surface.on("mousemove", onSurfaceMouseMove, surface); // mouse move for the entire surface
surface.on("mouseup", onSurfaceMouseUp, surface);
Cheers!
Frank