ZingChart Y Axis Label Formatting - zingchart

Is it possible in ZingChart to add a secondary y scale that uses the same values as the primary y scale, but just uses a simple conversion (e.g., anomaly degrees Celsius*1.8 = anomaly degrees Fahrenheit).
something like:
var chartConfig = {
scaleY2: { format: %v*1.8 }
}
Or, perhaps a function, like:
var chartConfig = {
scaleY2: { format: 'formatAxis()' }
}
...
formatAxis = function(p){ return { format:p.value*1.8 } }
I'm plotting temperature anomalies in degrees C on the primary y-axis. I'd like the degrees F to show up on the secondary y-axis.

You do indeed use a function. I just had a syntax error.
var chartConfig = {
scaleY2: { format: 'formatAxis()' }
}
...
window.formatAxis = function(v){
return (v*1.8).toFixed(2)+'\u00B0F';
}

The above answer from #magnum-π is correct. Creating a formatting function is the easiest and most effective solution.
// how to call function from ZingChart
let chartConfig = {
scaleY2: { format: 'formatAxis()' }
}
// defining function for ZingChart to find at the window scope
window.formatAxis = function(v){
return (v*1.8).toFixed(2)+'\u00B0F';
}
I have also configured a working demo of this to assist the above answer:
// window.onload event for Javascript to run after HTML
// because this Javascript is injected into the document head
window.addEventListener('load', () => {
// Javascript code to execute after DOM content
// full ZingChart schema can be found here:
// https://www.zingchart.com/docs/api/json-configuration/
let chartConfig = {
type: 'bar',
globals: {
fontSize: '14px',
},
title: {
text: 'Multiple Scales °C vs °F',
fontSize: '24px',
adjustLayout: true,
},
legend: {
draggable: true,
},
// plot represents general series, or plots, styling
plot: {
// hoverstate
tooltip: {
// % symbol represents a token to insert a value. Full list here:
// https://www.zingchart.com/docs/tutorials/chart-elements/zingchart-tokens/
text: '%kl was %v° %plot-text',
borderRadius: '3px',
// htmlMode renders text attribute as html so
// ° is rendered
htmlMode: true
},
valueBox: {
color: '#fff',
placement: 'top-in'
},
// animation docs here:
// https://www.zingchart.com/docs/tutorials/design-and-styling/chart-animation/#animation__effect
animation: {
effect: 'ANIMATION_EXPAND_BOTTOM',
method: 'ANIMATION_STRONG_EASE_OUT',
sequence: 'ANIMATION_BY_NODE',
speed: 275
}
},
plotarea: { margin: 'dynamic',},
scaleX: {
// set scale label
label: {
text: 'Days'
},
// convert text on scale indices
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
scaleY: {
// scale label with unicode character
label: {
text: 'Temperature (°C)'
}
},
scaleY2: {
label: {
text: 'Temperature (°F)'
},
guide: { visible: false }
},
// plot values
series: [
{
text: 'Celcius',
values: [23, 20, 27, 29, 25, 17, 15],
backgroundColor: '#448aff #64b5f6' ,
scales: 'scale-x, scale-y'
},
{
text: 'Farenheit',
values: [35, 42, 33, 49, 35, 47, 35].map(v => Number((v*1.8).toFixed(2))),
backgroundColor: '#ff5252 #e57373',
scales: 'scale-x, scale-y-2'
}
]
};
// render chart
zingchart.render({
id: 'myChart',
data: chartConfig,
height: '100%',
width: '100%',
});
});
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.chart--container {
min-height: 150px;
width: 100%;
height: 100%;
}
.zc-ref {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ZingSoft Demo</title>
<script src="https://cdn.zingchart.com/zingchart.min.js"></script>
</head>
<body>
<!-- CHART CONTAINER -->
<div id="myChart" class="chart--container">
<a class="zc-ref" href="https://www.zingchart.com/">Powered by ZingChart</a>
</div>
</body>
</html>

Related

How to implement a gauge solid chart in JSF

I'm new in JSF and I want to add a highchart solid gauge in my jsf page, but I implment the demo code and when I run it, it throws me this...
Error Parsing /index.xhtml: Error Traced[line: 185] El nombre de la entidad debe aparecer inmediatamente después de '&' en la referencia de entidades.
javax.faces.view.facelets.FaceletException: Error Parsing /index.xhtml: Error Traced[line: 185] El nombre de la entidad debe aparecer inmediatamente después de '&' en la referencia de entidades.
this is the code of the index
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/solid-gauge.js"></script>
<div style="width: 600px; height: 400px; margin: 0 auto">
<div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
<div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
</div>
<script type="text/javascript">
$(function () {
var gaugeOptions = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.1, '#55BF3B'], // green
[0.5, '#DDDF0D'], // yellow
[0.9, '#DF5353'] // red
],
lineWidth: 0,
minorTickInterval: null,
tickAmount: 2,
title: {
y: -70
},
labels: {
y: 16
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
}
}
}
};
// The speed gauge
var chartSpeed = Highcharts.chart('container-speed', Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 200,
title: {
text: 'Speed'
}
},
credits: {
enabled: false
},
series: [{
name: 'Speed',
data: [80],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
'<span style="font-size:12px;color:silver">km/h</span></div>'
},
tooltip: {
valueSuffix: ' km/h'
}
}]
}));
// The RPM gauge
var chartRpm = Highcharts.chart('container-rpm', Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 5,
title: {
text: 'RPM'
}
},
series: [{
name: 'RPM',
data: [1],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y:.1f}</span><br/>' +
'<span style="font-size:12px;color:silver">* 1000 / min</span></div>'
},
tooltip: {
valueSuffix: ' revolutions/min'
}
}]
}));
// Bring life to the dials
setInterval(function () {
// Speed
var point,
newVal,
inc;
if (chartSpeed) {
point = chartSpeed.series[0].points[0];
inc = Math.round((Math.random() - 0.5) * 100);
newVal = point.y + inc;
if (newVal < 0 || newVal > 200) {
newVal = point.y - inc;
}
point.update(newVal);
}
// RPM
if (chartRpm) {
point = chartRpm.series[0].points[0];
inc = Math.random() - 0.5;
newVal = point.y + inc;
if (newVal < 0 || newVal > 5) {
newVal = point.y - inc;
}
point.update(newVal);
}
}, 2000);
});
</script>
</h:body>
</html>
I don't know what I'm doing wrong, hope somebody can help me
JSF using Facelets is based on XML so the ampersands (&) are gonna be taken as an entity instead of the and conditional operator in java and most programming languages. so If you want to use it in your facelets you must change all the & with & which is the ampersand entity.
This problem is caused by not using CData. You should use CDATA for this
//<![CDATA[
//javascript code
//]]>
what does mean CDATA What does <![CDATA[]]> in XML mean?

How to resize svg shape based on text content

I would like to have svg shape scale based on text content of text area or text-input. As the text content increases, the size of the underlying svg element should increase as well
This is what I have so far:
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#myholder'),
width: 1330,
height: 660,
model: graph,
gridSize: 1,
defaultLink: new joint.dia.Link({
attrs: {'.marker-target': {d: 'M 10 0 L 0 5 L 10 10 z'}}
}),
validateConnection: function (cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
// Prevent linking from input ports.
if (magnetS && magnetS.getAttribute('type') === 'input')
return false;
// Prevent linking from output ports to input ports within one element.
if (cellViewS === cellViewT)
return false;
// Prevent loop linking
return (magnetS !== magnetT);
// Prevent linking to input ports.
return magnetT && magnetT.getAttribute('type') === 'input';
},
// Enable marking available cells & magnets
markAvailable: true,
//Enable link snapping within 75px lookup radius
// snapLinks: {radius: 75},
interactive: function (cellView, methodName)
{
if (cellView.model.get('isInteractive') === false)
return false;
// return true;
}
});
joint.shapes.devs.CircleModel = joint.shapes.devs.Model.extend({
markup: '<g class="rotatable"><g class="scalable"><circle class="body"/></g><text class="label"/><g class="inPorts"/><g class="outPorts"/></g>',
// portMarkup: '<g class="port port<%=1%>"><rect class="port-body"/><text class="port-label"/></g>',
defaults: joint.util.deepSupplement({
type: 'devs.CircleModel',
attrs: {
'.body': {r: 50, cx: 50, stroke: '', fill: 'white'},
'.label': {text: '', 'ref-y': 0.5, 'y-alignment': 'middle'},
'.port-body': {r: 3, width: 10, height: 10, x: -5, stroke: 'gray', fill: 'lightgray', magnet: 'active'}
}
}, joint.shapes.devs.Model.prototype.defaults)
});
joint.shapes.devs.CircleModelView = joint.shapes.devs.ModelView;
var rect = new joint.shapes.basic.Rect({
isInteractive: false,
position: {x: 10, y: 50},
size: {width: 51, height: 41},
attrs: {rect: {fill: '#D6F2FC', stroke: '#7E7E7E'}, '.': {magnet: false}}
});
// Create a custom element.
// ------------------------
joint.shapes.html = {};
joint.shapes.html.Element = joint.shapes.basic.Rect.extend({
defaults: joint.util.deepSupplement({
type: 'html.Element',
attrs: {
rect: {stroke: 'none', 'fill-opacity': 0}
}
}, joint.shapes.basic.Rect.prototype.defaults)
});
// Create a custom view for that element that displays an HTML div above it.
// -------------------------------------------------------------------------
joint.shapes.html.ElementView = joint.dia.ElementView.extend({
template: [
'<div class="html-element">',
'<button class="delete">x</button>',
'<span></span>', '<br/>',
// '<input type="text" value="" />',
'<textarea id="txt" type="text" rows="10" value="Start writing"></textarea>',
'</div>'
].join(''),
initialize: function () {
_.bindAll(this, 'updateBox');
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
this.$box = $(_.template(this.template)());
// Prevent paper from handling pointerdown.
this.$box.find('input,select').on('mousedown click', function (evt) {
evt.stopPropagation();
});
this.$ruler = $('<span>', {style: 'visibility: hidden; white-space: pre'});
$(document.body).append(this.$ruler);
// This is an example of reacting on the input change and storing the input data in the cell model.
this.$box.find('textarea').on('input', _.bind(function (evt) {
var val = $(evt.target).val();
this.model.set('textarea', val);
this.$ruler.html(val);
var width = this.$ruler[0].offsetWidth;
var height = this.$ruler[0].offsetHeight;
var area = width * height;
height = area / 150;
width = 150;
if ((area > 9000))
{
this.model.set('size', {width: width + 50, height: height + 80});
this.$box.find('textarea').css({width: width, height: height + 30});
// this.$box.find('.color-edit').css({width: width + 50, height: height + 80});
this.$box.find('.in').css({top: height + 75});
}
}, this));
this.$box.find('textarea').on('click', _.bind(function () {
this.$box.find('.delete').css({opacity: 1});
this.$box.find('textarea').css({opacity: 1});
}, this));
this.$box.find('textarea').on('blur', _.bind(function () {
this.$box.find('.delete').css({opacity: 0});
this.$box.find('textarea').css({opacity: 0});
}, this));
this.$box.find('.delete').on('click', _.bind(this.model.remove, this.model));
// Update the box position whenever the underlying model changes.
this.model.on('change', this.updateBox, this);
// Remove the box when the model gets removed from the graph.
this.model.on('remove', this.removeBox, this);
this.updateBox();
this.listenTo(this.model, 'process:ports', this.update);
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
},
render: function () {
joint.dia.ElementView.prototype.render.apply(this, arguments);
this.paper.$el.prepend(this.$box);
this.updateBox();
return this;
},
updateBox: function ()
{
// Set the position and dimension of the box so that it covers the JointJS element.
var bbox = this.model.getBBox();
// Example of updating the HTML with a data stored in the cell model.
this.$box.find('label').text(this.model.get('label'));
this.$box.find('span').text(this.model.get('select'));
this.$box.css({width: bbox.width + 6, height: bbox.height, left: bbox.x, top: bbox.y, transform: 'rotate(' + (this.model.get('angle') || 0) + 'deg)'});
},
removeBox: function (evt) {
this.$ruler.remove();
this.$box.remove();
}
});
paper.on('cell:pointerdblclick', function (cellView, evt, x, y)
{
var clone = cellView.model.clone();
if (rect.id === cellView.model.id)
{
clone = new joint.shapes.html.Element({
position: {x: 100, y: 60},
size: {width: 81, height: 69},
inPorts: [''],
outPorts: [''],
attrs: {
'.': {magnet: true},
'.label': {text: '', 'ref-x': .4, 'ref-y': .2},
'.inPorts circle': {type: 'input'},
'.outPorts circle': {type: 'output'},
'.port-body': {r: 3}
}
});
// clone.resize(2*81,2*39)
graph.addCell(clone);
}
});
// // First, unembed the cell that has just been grabbed by the user.
paper.on('cell:pointerdown', function (cellView, evt, x, y) {
var cell = cellView.model;
if (!cell.get('embeds') || cell.get('embeds').length === 0) {
// Show the dragged element above all the other cells (except when the
// element is a parent).
cell.toFront();
_.invoke(graph.getConnectedLinks(cell), 'toFront');
}
if (cell.get('parent')) {
graph.getCell(cell.get('parent')).unembed(cell);
}
});
// When the dragged cell is dropped over another cell, let it become a child of the
//element below.
paper.on('cell:pointerup', function (cellView, evt, x, y) {
if (cellView.model.isLink())
return;
var cell = cellView.model;
var cellViewsBelow = paper.findViewsFromPoint(cell.getBBox().center());
if (cellViewsBelow.length) {
// Note that the findViewsFromPoint() returns the view for the `cell` itself.
var cellViewBelow = _.find(cellViewsBelow, function (c) {
return c.model.id !== cell.id;
});
// Prevent recursive embedding.
if (cellViewBelow && cellViewBelow.model.get('parent') !== cell.id) {
cellViewBelow.model.embed(cell);
}
}
});
graph.addCells([rect]);
Could not find a solution elsewhere. Any help would be appreciated. thanks
You have to make the HTML Input resize based on the text inside.
Auto-scaling input[type=text] to width of value?
The ElementView has to listen to the HTML Input changes (input event) and update the size of the model based on the width and height of the HTML Input.
Example:
function onTextInput(evt) {
var $input = $(evt.target);
// 1. auto-scaling the input based on the text inside.
$input.attr('size', Math.max($input.val().length, 10));
// 2. resizing the model to the size of the input + padding.
model.resize($input.outerWidth() + 5, $input.outerHeight() + 40);
}
$('input').on('input', onTextInput);
JS Fiddle: http://jsfiddle.net/kumilingus/Lrffgvqn/
Similar with HTML TextArea, where the only difference will be the way how you auto-scale it based on the text inside.

How can I add different images instead of text inside d3.js piechart slices

Instead of the piedata variable being populated with text as it is now, I need to have the hrefs for the 5 different images. Now I have only one and it is hardcoded below rather than being pulled from the variable piedata.
I also need to have an image in the center of the circle. Ideas please
<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js" ></script>
<head>
</head>
<body>
<style>
path {
stroke: #fff;
fill-rule: evenodd;
}
text {
font-family: Arial, sans-serif;
font-size: 12px;
}
</style>
<script>
var width = 550,
height = 550,
radius = 250
colors = d3.scale.ordinal()
.range(['#336699 ','#336699 ','#ACD1E9','#ACD1E9','#ACD1E9']);
var piedata = [
{ label: "test",
value: 50 },
{ label: "",
value: 50},
{ label: "Jonathan",
value: 50},
{ label: "Lorenzo",
value: 50},
{ label: "Hillary",
value: 50}
]
var pie = d3.layout.pie()
.value(function(d) {
return d.value;
})
var arc = d3.svg.arc()
.outerRadius(250)
.innerRadius(100)
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate('+(width-radius)+','+(height-radius)+')')
.selectAll('path').data(pie(piedata))
.enter().append('g')
.attr('class', 'slice')
var slices = d3.selectAll('g.slice')
.append('path')
.attr('fill', function(d, i) {
return colors(i);
})
.attr('d', arc)
var imgs = svg.selectAll("image").data([0])
imgs.enter()
.append("svg:image")
.attr("xlink:href", "http:/images/home-activities_09.jpg")
.attr("x", "110")
.attr("y", "35")
.attr("width", "40")
.attr("height", "40");
If all images are of constant width and height, you simply add the image URLs to your data array and dynamically set the xlink:href attribute using the data function.
var piedata = [
{
label: "test",
image: "http://placeimg.com/40/40/any",
value: 50
},
{
label: "",
image: "http://placeimg.com/42/42/any",
value: 50
},
{
label: "Jonathan",
image: "http://placeimg.com/44/44/any",
value: 50
},
{
label: "Lorenzo",
image: "http://placeimg.com/46/46/any",
value: 50
},
{
label: "Hillary",
image: "http://placeimg.com/38/38/any",
value: 50
}
]
....
g.append("g")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.append("svg:image")
.attr("xlink:href",function(d) {return d.data.image;})
.attr("width",image_width)
.attr("height",image_height)
.attr("x",-1*image_width/2)
.attr("y",-1*image_height/2);
Here's a working fiddle: http://jsfiddle.net/LLwr4q7s/
If, on the other hand, each image is a different size and you don't know what the width and height values are beforehand, some additional work is involved. One approach is to preload the images so that you know the width and height values once the images are loaded, and use a callback function to place them within the pie chart.
Here's an example fiddle with dynamic image dimensions: http://jsfiddle.net/LLwr4q7s/2/

How to change color of bar in column chart with different level of percentage in highcharts

I want to change the color of the bar column at different percentage. Suppose there are 10 columns to be represented in the column graph. out of which 3 are below 60% and 5 are above 60% and 2 are above 80%. the columns that are below 60% should pick the color green, column that are above 60% should pick up the color amber and those are above 80% should pick red.
Please help me...
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function () {
var chart;
var input = [34.4, 62.5, 80.1, 70, 69.6, 69.5, 89.1, 68.4, 18,
17.3],
data = [],
categories = ['orcl1 ','orcl2 ','orcl3 ','orcl4 ','orcl5 ','orcl6 ','orcl7 ','orcl8 ','orcl9 ','orcl10 '];
$.each(input, function(index, value){
var color;
if (value > 80) color = 'red';
else if (value > 60) color = 'Orange';
else color = 'green';
data.push({y:value, color: color, url:'https://www.google.com'});
});
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'COL',
type: 'column'
},
title: {
text: 'Current Top 10 CPU Consumers',
style: {fontSize: '10px'}
},
xAxis: {
categories: categories,
labels: {
rotation: -35,
align: 'center'
}
},
yAxis: {
title: {
text: 'Percentage',
style: {fontSize: '11px'}
}
},
exporting: { enabled: false },
legend: {
enabled: false,
},
tooltip: {
formatter: function() {
return '<b>'+ this.x +'</b>' +'- Oracle User Process CPU Consumed :'+'<b>'+ this.y +' % ' +'</b>' ;
}
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
location.href = this.options.url;
}
}
}
}
},
series: [{
name: 'CPU Consumed',
pointWidth: 28,
data: data
}]
});
});
});
</script>
</head>
<body>
<script src="../../js/highcharts.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="COL" style="min-width: 100px; height: 300px; margin: 0 auto"></div>
</body>
</html>
You'll need to preprocess the data to assign the colors. Something like this:
var input = [34.4, 62.5, 80.1, 70, 69.6, 69.5, 89.1, 68.4, 18,
17.3],
data = [];
$.each(input, function(index, value){
var color;
if (value > 80) color = 'red';
else if (value > 65) color = 'yellow';
else color = 'green';
data.push({y:value, color: color});
});
http://jsfiddle.net/btwCb/

JQuery Flot doesn't draw bar chart + how to display values from data in tooltip?

I have a problem with JQuery Flot chart. It doesn't show the bar chart (data_campaigns) at all but the (data_campaigns2) shows up just fine.
I would also like to know how to show data from both charts in tooltip. Now the tooltip is just showing random X and Y variables but I would like it show the amount of clicks.
//Chart - Campaigns
$(function () {
var data_campaigns = [
[1359766800,8],[1359853200,4],[1359939600,11],[1360026000,11],
[1360112400,15],[1360198800,12],[1360285200,16],[1360371600,7],
[1360458000,9],[1360544400,6],[1360630800,13],[1360717200,12],
[1360803600,6],[1360890000,13],[1360976400,3],[1361062800,9],
[1361149200,18],[1361235600,18],[1361322000,12],[1361408400,14],
[1361494800,7],[1361581200,5],[1361667600,3],[1361754000,9],
[1361840400,15],[1361926800,14],[1362013200,4],[1362099600,0],
[1362186000,0],[1362272400,0]];
var data_campaigns2 = [
[1359766800,8],[1359853200,4],[1359939600,11],[1360026000,11],
[1360112400,15],[1360198800,12],[1360285200,16],[1360371600,7],
[1360458000,9],[1360544400,6],[1360630800,13],[1360717200,12],
[1360803600,6],[1360890000,13],[1360976400,3],[1361062800,9],
[1361149200,18],[1361235600,18],[1361322000,12],[1361408400,14],
[1361494800,7],[1361581200,5],[1361667600,3],[1361754000,9],
[1361840400,15],[1361926800,14],[1362013200,4],[1362099600,0],
[1362186000,0],[1362272400,0]];
var plot = $.plot($("#placeholder"),
[ { data: data_campaigns,color:"rgba(0,0,0,0.2)", shadowSize:0,
bars: {
show: true,
lineWidth: 0,
fill: true,
fillColor: { colors: [ { opacity: 1 }, { opacity: 1 } ] }
}
} ,
{ data: data_campaigns2,
color:"rgba(255,255,255, 0.4)",
shadowSize:0,
lines: {show:true, fill:false}, points: {show:false},
bars: {show:false},
}
],
{
series: {
bars: {show:true, barWidth: 0.6}
},
grid: { show:false, hoverable: true, clickable: false, autoHighlight: true, borderWidth:0 },
yaxis: {
min: 0
},
xaxis: {
tickDecimals: 0
}
});
function showTooltip(x, y, contents) {
console.log(x+","+y);
var d = new Date(contents *1000);
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
$('<div id="tooltip"><div class="date">'+curr_date + "." + curr_month + "." + curr_year+'<\/div><div class="title text_color_3">'+x+'%<\/div> <div class="description text_color_3">CTR<\/div><div class="title ">'+y+'<\/div><div class="description">Clicks<\/div><\/div>').css( {
position: 'absolute',
display: 'none',
top: y - 125,
left: x - 40,
border: '0px solid #ccc',
padding: '2px 6px',
'background-color': '#fff',
opacity: 10
}).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 (item) {
if (previousPoint != item.dataIndex) {
previousPoint = item.dataIndex;
$("#tooltip").remove();
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showTooltip(item.pageX, item.pageY,
x);
}
}
});
1) the x, y parameters in function showTooltip(x, y, contents)
are actually not x,y values from your chart, bude x, y coordinates where to place the tooltip at. The tooltip value (text displayed in tooltip) is in parameter contents, so instead of:
$('<div id="tooltip"><div class="date">'+curr_date + "." + curr_month + "." + curr_year+'<\/div><div class="title text_color_3">'+x+'%<\/div> <div class="description text_color_3">CTR<\/div><div class="title ">'+y+'<\/div><div class="description">Clicks<\/div><\/div>').css( {...
you need something like this:
$('<div id="tooltip">' + contents + '<\/div>').css({...
with contents variable filled with whatever you need.
2) you need to set mode option
xaxis: {
mode: 'time',
...
}
and play a bit with the options to display bars. in the jsfiddle example below i set the lineWidth: 10 and changed some colors
3) Blake's advice about the timestamps is right. (not solving the bar visibility, but solving the correct x axis date values), when populating the data array, multiply them by 1000 to be displayed correctly
here is the jsFiddle, have a look at it

Resources