How to change text in multiple lines / places of a Textbox in FabricJS? - algorithm

I need to replace text of particular selection when the input value has been changed.
On the initial rendering, I get an object of selections and fields.
Secondly, inputs get values of fields.
Assume I'm changing a value of the Line input, since this field controls two lines, both of those green texts should be replaced with the new one.
http://jsfiddle.net/hkvmLwfu/
Tnx
////////////////////////////////////////////////////////////////////////
/////////////// THIS FUNCTION NEEDS TO BE DEVELOPED ////////////////////
////////////////////////////////////////////////////////////////////////
function replaceTextBySelection(fieldId, fieldValue, canvas, text){
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
var canvas = new fabric.Canvas('paper');
canvas.setHeight(300);
canvas.setWidth(500);
var text = new fabric.Textbox('Sample Line 1 Line 2 Line 3', {
left: 50,
top: 10,
fontFamily: 'arial',
fill: '#333',
fontSize: 50
});
canvas.add(text);
canvas.renderAll();
const fields = {
FIELD_1: {
value: "Sample",
color: '#F00'
},
FIELD_2: {
value: "Line",
color: '#0F0'
}
}
selections = [
{
rowId: 0,
offset: 0,
length: 6,
field: "FIELD_1"
},
{
rowId: 1,
offset: 0,
length: 4,
field: "FIELD_2"
},
{
rowId: 2,
offset: 0,
length: 4,
field: "FIELD_2"
}
]
selections.map((obj)=>{
text.setSelectionStart(obj.offset);
text.setSelectionEnd(obj.offset + obj.length);
text.setSelectionStyles();
for (let i = text.selectionStart; i < text.selectionEnd; i++) {
text.insertCharStyleObject(obj.rowId, i, {
textBackgroundColor: fields[obj.field].color
})
}
canvas.renderAll();
return obj;
});
$('#FIELD_1').val( fields['FIELD_1'].value );
$('#FIELD_2').val( fields['FIELD_2'].value );
$("input").keyup(function(t){
replaceTextBySelection(this.id, this.value, canvas, text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.min.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
<input type="text" id="FIELD_1" />
<br/>
<input type="text" id="FIELD_2" />

Your example complicates things because the selections object reasons about rows, but the text doesn't actually contain rows, only spaces that get wrapped to a new line.
It gets easier if you define your text instead as
var text = new fabric.Textbox('Sample\nLine 1\nLine 2\nLine 3', {
left: 50,
top: 10,
fontFamily: 'arial',
fill: '#333',
fontSize: 50
});
Using this text I have created a functional example: http://jsfiddle.net/hkvmLwfu/12/. I'm not sure this is entirely how you want it, but you should be able to pick it up from here.

Just use \n where you want to break the line. It will work like <br/>.

Related

Amcharts5 Floating Barchart over two axes

I started off with this example: https://www.amcharts.com/demos/floating-bar-chart/ but want the floating-aspect also cover a date axis. This way I will be able to color a rectangular area in my charts.
I made the following changes:
Changed the x-axis to a date axis
Changed the y-axis to a value axis
Changed the data correspondingly
Changed the data-fields in the series-definition to use openValueXField, valueXField for the dates and openValueYField and valueYField for the values
Something (vertical colored lines) are displayed in the most left part of the chart but no colored areas.
When using values for both axes it works perfectly but not with dates. I hope some of you knows what is wrong here. The Amcharts Demo's only provide example with one axis.
The two source codes are included hereafter.
//
// Source Code for two numeric axis -> working
//
<meta content="text/html;charset=utf-6" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<!-- Chart code -->
<script>
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
layout: root.verticalLayout
}));
// Add legend
// https://www.amcharts.com/docs/v5/charts/xy-chart/legend-xy-series/
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.p50,
x: am5.p50
}))
var colors = chart.get("colors");
// Data
var data = [{
name: "John",
startTime: 8,
endTime: 11,
startValue: 10,
endValue: 14,
columnSettings: {
stroke: colors.getIndex(1),
fill: colors.getIndex(1)
}
}, {
name: "Joe",
startTime: 10,
endTime: 13,
startValue: 12,
endValue: 17,
columnSettings: {
stroke: colors.getIndex(3),
fill: colors.getIndex(3)
}
}];
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {pan:"zoom"}),
})
);
var xAxis = chart.xAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererX.new(root, {pan:"zoom"}),
})
);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Income",
xAxis: xAxis,
yAxis: yAxis,
openValueXField: "startTime",
valueXField: "endTime",
openValueYField: "startValue",
valueYField: "endValue",
sequencedInterpolation: true
}));
series.columns.template.setAll({
height: am5.percent(100),
templateField: "columnSettings",
tooltipText: "[bold]{name}[/]\n{categoryY}: {valueX}"
});
series.data.setAll(data);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear();
chart.appear(1000, 100);
}); // end am5.ready()
</script>
<!-- HTML -->
<div id="chartdiv"></div>
91,31 43%
//
// Source Code for one date and one numeric axis -> NOT working
//
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<!-- Chart code -->
<script>
am5.ready(function() {
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
panX: false,
panY: false,
wheelX: "panX",
wheelY: "zoomX",
layout: root.verticalLayout
}));
// Add legend
// https://www.amcharts.com/docs/v5/charts/xy-chart/legend-xy-series/
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.p50,
x: am5.p50
}))
var colors = chart.get("colors");
// Data
var data = [{
name: "John",
startTime: new Date(2021, 1, 28),
endTime: new Date(2021, 3, 17),
startValue: 10,
endValue: 14,
columnSettings: {
stroke: colors.getIndex(1),
fill: colors.getIndex(1)
}
}, {
name: "Joe",
startTime: new Date(2021, 2, 5),
endTime: new Date(2021, 5, 7),
startValue: 12,
endValue: 17,
columnSettings: {
stroke: colors.getIndex(3),
fill: colors.getIndex(3)
}
}];
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var yAxis = chart.yAxes.push(
am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {pan:"zoom"}),
})
);
var xAxis = chart.xAxes.push(
am5xy.DateAxis.new(root, {
renderer: am5xy.AxisRendererX.new(root, {
pan:"zoom",
minimumDate: new Date(2021, 1, 18),
maximumDate: new Date(2021, 7, 20),
}),
})
);
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Income",
xAxis: xAxis,
yAxis: yAxis,
openValueXField: "startTime",
valueXField: "endTime",
openValueYField: "startValue",
valueYField: "endValue",
sequencedInterpolation: true
}));
series.columns.template.setAll({
height: am5.percent(100),
templateField: "columnSettings",
tooltipText: "[bold]{name}[/]\n{categoryY}: {valueX}"
});
series.data.setAll(data);
// Make stuff animate on load
// https://www.amcharts.com/docs/v5/concepts/animations/
series.appear();
chart.appear(1000, 100);
}); // end am5.ready()
</script>
<!-- HTML -->
<div id="chartdiv"></div>
94,3 97%

Kendo jQuery Inline Grid Validation is not working as needed

I'm trying to use KENDO UI to validated 2 values in a grid row.
These 2 values, HOURS and COUNT are mutually exclusive, so if they both have a value > 0, I would like to signal an error.
Two behavior issues I'm having:
The error "Both Hours and Count are not allowed" displays, but it only triggers on the second iteration of erroneous input.
Example input: Hours / Count
1 0 (good)
1 1 (should result an error)
1 2 (this fires the desired error)
Once the error displays, I can't determine how to remove it. If I correct the data setting one of the inputs back to zero, the error remains.
I'm using function FCTest to validate, but I can only assume I need to call it again, or in a different sequence to get the timing corrected.
Thanks,
Robert
My Code:
<!DOCTYPE html>
<!-- TEST -->
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/grid/editing-custom-validation">
<style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.504/styles/kendo.common-material.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.2.504/styles/kendo.material.min.css" />
<script src="//kendo.cdn.telerik.com/2016.2.504/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2016.2.504/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<script>
$(document).ready(function () {
dataSource = new kendo.data.DataSource({
data: [
{ id: 1, count: 1, hours: 0},
{ id: 2, count: 0, hours: 1},
],
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
id: { editable: false },
count: {editable: true,type: "number",
validation:{
required:true,
maxlength:"3",
FCValid: FCTest}},
hours: {editable: true, type: "number",
validation:{required:true,
maxlength:"2"}}}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
{field: "id", title: "ID", format: "{0:c}", width: "120px"},
{field: "count", title: "Count", width: "120px"},
{field: "hours", title: "Hours", width: "120px"},
{command: ["edit", "destroy"], title: " ", width: "250px"}],
editable: "inline"
});
}); // end document ready
function FCTest(input) {
var row = input.closest("tr");
var grid = row.closest("[data-role=grid]").data("kendoGrid");
var dataItem = grid.dataItem(row);
// if (parseFloat(input.val()) <= .1) {
// input.attr("data-FCValid-msg", "Decimals not allowed");
// return false;
// }
console.log({row});
console.log({dataItem});
console.log(dataItem.hours);
console.log(dataItem.count);
if (parseFloat(dataItem.hours) > 0 && (parseFloat(dataItem.count) > 0)) {
input.attr("data-FCValid-msg", "Both Hours and Count are not allowed");
return false;
}
if (parseFloat(dataItem.hours) == 0 && (parseFloat(dataItem.count) == 0)) {
input.attr("data-FCValid-msg", "Must contain one Frequency value: Hours or Count");
return false;
}
return true;
}
</script>
</body>
</html>
Subscribe to the cellClose, check if the incoming model is not a new row, and then check if the values meet your conditions:
cellClose: function(e) {
if (!e.model.isNew()) {
if (e.model.count > 0 && e.model.hours > 0) {
kendo.alert('Both Hours and Count are not allowed');
} else if (e.model.count == 0 && e.model.hours == 0) {
kendo.alert('Must contain one Frequency value: Hours or Count');
}
}
}
Dojo: https://dojo.telerik.com/oxAkUpAs

datamaps.js: Animate bubble remove after new data gets loaded

When we update new data on .bubbles([]) all the previous bubble disappears immediately. Can we make the bubble remain there for some time and then remove them from the map using jquery animation and also display a new bubbles at certain time periods?
Below is the code:
`
</head>
<body>
<div id="container" style="position: relative; width: 100%; height: 600px"></div>
</body>
<script type="text/javascript">
var bombMap = new Datamap({
element: document.getElementById('container'),
fills: {
'USA': '#1f77b4',
'RUS': '#9467bd',
'PRK': '#ff7f0e',
'PRC': '#2ca02c',
'IND': '#e377c2',
'GBR': '#8c564b',
'FRA': '#d62728',
'PAK': '#7f7f7f',
defaultFill: '#c1b9bb' //any hex, color name or rgb/rgba value
},
geographyConfig: {
highlightOnHover: false,
popupOnHover: false
},
scope: 'world',
data: {
'RUS': {fillKey: 'RUS'},
'PRK': {fillKey: 'PRK'},
'PRC': {fillKey: 'PRC'},
'IND': {fillKey: 'IND'},
'GBR': {fillKey: 'GBR'},
'FRA': {fillKey: 'FRA'},
'PAK': {fillKey: 'PAK'},
'USA': {fillKey: 'USA'}
},
bubbleConfig: {
borderWidth: 2,
borderColor: '#FFFFFF',
popupOnHover: false,
fillOpacity: 0.45,
highlightOnHover: true,
highlightFillColor: '#FC8D59',
highlightBorderColor: 'rgba(250, 15, 160, 0.2)',
highlightBorderWidth: 2,
highlightFillOpacity: 0.85,
}
});
var bombs = [{
name: 'Joe 4',
radius: 10,
yeild: 400,
country: 'USSR',
fillKey: 'RUS',
significance: 'First fusion weapon test by the USSR (not "staged")',
date: '1953-08-12',
latitude: 50.07,
longitude: 78.43
},{
name: 'RDS-37',
radius: 10,
yeild: 1600,
country: 'USSR',
fillKey: 'RUS',
significance: 'First "staged" thermonuclear weapon test by the USSR (deployable)',
date: '1955-11-22',
latitude: 50.07,
longitude: 78.43
},
];
var options = {
popupTemplate: function (geo, data) {
return ['<div class="hoverinfo">' + data.name,
'<br/>Payload: ' + data.yeild + ' kilotons',
'<br/>Country: ' + data.country + '',
'<br/>Date: ' + data.date + '',
'</div>'].join('');
}
};
bombMap.bubbles(bombs, options);
setInterval(function(){
console.log('removing elements');
bombMap.bubbles([{
name: 'Tsar Bomba',
radius: 10,
yeild: 50000,
country: 'USSR',
fillKey: 'RUS',
significance: 'Largest thermonuclear weapon ever tested—scaled down from its initial 100 Mt design by 50%',
date: '1961-10-31',
latitude: 73.482,
longitude: 54.5854
}]);
},3000);
</script>
Source: https://github.com/markmarkoh/datamaps
Yes, you should be able to do this by using d3 to select all the current circles (bubbles) that are on your datamap. You can then use a d3 transition to fade your circles to a fill-opacity of 0.0001 before loading your new array of bubbles.

Why connection line shows away from Div in JSPlumb?

This is my JSFiddle
Query - When I am trying to establish the connnection between IDs A1 and B the connection pink line shows away from Div B. Below the pink line highlighted is away from Div B. This is the problem
JQuery
//Setting up drop options
var targetDropOptions = {
};
connectorHoverStyle = {
lineWidth: 7,
strokeStyle: "#2e2aF8",
cursor: 'pointer'
}
//Setting up a Target endPoint
var targetColor = "#316b31";
var targetEndpoint = {
anchor: "LeftMiddle",
endpoint: ["Dot", { radius: 8}],
paintStyle: { fillStyle: targetColor },
//isSource: true,
scope: "green dot",
connectorStyle: { strokeStyle: targetColor, lineWidth: 8 },
connector: ["Flowchart", { curviness: 63}],
maxConnections: -1,
isTarget: true,
dropOptions: targetDropOptions,
connectorHoverStyle: connectorHoverStyle
};
//Setting up a Source endPoint
var sourceColor = "#ff9696";
var sourceEndpoint = {
anchor: "RightMiddle",
endpoint: ["Dot", { radius: 8}],
paintStyle: { fillStyle: sourceColor },
isSource: true,
scope: "green dot",
connectorStyle: { strokeStyle: sourceColor, lineWidth: 4 },
connector: ["Flowchart", { curviness: 63}],
maxConnections: -1,
// isTarget: true,
dropOptions: targetDropOptions,
connectorHoverStyle: connectorHoverStyle
};
jsPlumb.bind("ready", function () {
jsPlumb.animate($("#A"), { "left": 50, "top": 100 }, { duration: "slow" });
jsPlumb.animate($("#B"), { "left": 300, "top": 100 }, { duration: "slow" });
jsPlumb.animate($("#C"), { "left": 540, "top": 100 }, { duration: "slow" });
jsPlumb.animate($("#D"), { "left": 780, "top": 100 }, { duration: "slow" });
var window = jsPlumb.getSelector('.window');
jsPlumb.addEndpoint(window, targetEndpoint);
jsPlumb.addEndpoint(window, sourceEndpoint);
jsPlumb.addEndpoint(jsPlumb.getSelector('#A1'), sourceEndpoint, targetEndpoint);
jsPlumb.draggable(window);
jsPlumb.importDefaults({
ConnectionOverlays: [
["Arrow", { location: 0.8}],
["Label", {
location: 0.5,
id: "label",
cssClass: "aLabel"
}]
]
});
});
HTML
<div id="A" class="a window" style="width: 100px; height: 100px; border: solid 1px;">
<strong>A</strong>
<div id="A1">
</div>
</div>
<div id="B" class="b window" style="width: 100px; height: 100px; border: solid 1px;">
<strong>B</strong>
</div>
<div id="C" class="c window" style="width: 100px; height: 100px; border: solid 1px;">
<strong>C</strong>
</div>
<div id="D" class="d window" style="width: 100px; height: 100px; border: solid 1px;">
<strong>D</strong>
</div>
I wanted to have multiple Anchors on the same Div provided ID should be the attributes for those anchors somehow.
In order to accomplish this. I first removed the extra div. Now Suppose somebody wants to display two Source Anchors. For that I made modification in
jquery.jsPlumb-1.3.16-all-min.js file
Following was the Original line of code in this file
this.makeNode = function (E, D) {
return f("circle", { cx: E[2] / 2, cy: E[3] / 2, r: E[2] / 2
}
Modification is below. I am now adding id attributes to each anchor(circle).
this.makeNode = function (E, D) {
var attr = $('#'+obj[0].endpoint.elementId).attr('actionID');
return f("circle", { cx: E[2] / 2, cy: E[3] / 2, r: E[2] / 2, id: attr
}
How am I getting the value of id ?
In, the Div shown above in the query, I added an Attribute Action and assigned some ID that I want to assign. Like below
jsPlumb.getSelector('#first').attr('actionID', 'p1');
and finally adding the EndPoint
jsPlumb.addEndpoint(jsPlumb.getSelector('#first'), sourceEndpoint);
Similarly, I can assign as many distinct Anchors in terms of IDs as much required.
jsPlumb.getSelector('#first').attr('actionID', 'p3');
jsPlumb.addEndpoint(jsPlumb.getSelector('#first'), [TopMiddle]);
How will you assign the Source ID and target ID on Connection ?
jsPlumb.bind("jsPlumbConnection", function (CurrentConnection) {
if (CurrentConnection.connection.targetId ==
CurrentConnection.connection.sourceId)
jsPlumb.detach(CurrentConnection.connection);
else {
var obj = CurrentConnection.sourceEndpoint.canvas.children[0].firstChild.id;
init(CurrentConnection.connection, obj);
}
});
init = function (connection, CircleID) {
connection.getOverlay("label").setLabel(CircleID + "-" + connection.targetId);
};
Hope this will be helpful to those users facing the same issue...

How to use Jqplot to show two groups of differently colored bars in the same stacked bar chart

I want to make a bar chart with two sets of stacked bars which are grouped together to compare the two groups of stacked bars. This should be displayed in the following manner:
I have gone through this link
But it didn't help me plot something like you see in the above image. I even tried sending two data sets like [[s1, s2, s3], [s4, s5, s6]] But it didn't help me plot the chart.
Does anyone know how to do it?
Any help will be greatly appreciated.
Thanks in advance.
Setting the option stackSeries: true will create the desired display for bar charts.
Official sources:
jqPlot Source code: source code, version 1.0.8r1250 of
2013-03-27. For this issue, src/jqplot.core.js lines 2499, 2563, and 2649.
jqPlot Documentation: It says that the API Documentation is most accurate. you can also see the webpage, README.txt,
optionsTutorial.txt, jqPlotOptions.txt, jqPlotOptions.txt,
jqPlotCssStyling.txt, usage.txt, changes.txt in the 1.0.8r1250
general release
The jqPlot documentation is not up to date so I took a look at the source code. Unfortunately, there is no way to directly have two sets of bars with a stacked-bar chart. The jqPlot.stackSeries property is only a boolean value. It's only function is to tell jqPlot to stack each series on top of each other for as many bars as there are values in the different series. Each series is plotted one value per bar with the first series being on the bottom. In other words, all [0] values are plotted in the first bar, [1] values in the second, etc. The amount shown within the bar is the sum of the [n] value for the current series and all prior series. There is no way to specify that there are two, or more, groupings of series. The capability to do what is desired just does not exist in jqPlot.
But you can accomplish what you desire:
The fact that jqPlot does not natively support what you want does not mean that you can not do it, merely that you need to get creative.
The graph you desire can be looked at as being two separate graphs that have been overlaid upon each other with spacing between the bars on the individual graphs permitting enough space (seriesDefaults.rendererOptions.barMargin) for the bars from the other graph to be overlaid next to them.
You can use jqPlot to create:
That graph has the scale, background and grid-lines you desire set to be visible. Note that the graph has an extra bar in it. This is needed to provide enough background and grid-lines for the last bar provided by the other graph.
You can also use jqPlot to create the second graph:
This graph has the scale and grid-lines set in jqPlot to not be visible.
seriesDefaults.axes.xaxis.tickOptions.show = false;
seriesDefaults.axes.yaxis.tickOptions.show = false;
etc.
The background is set to be transparent. Note that you are going to need to offset the position of this graph somewhat to the right when positioning the <div> relative to the first graph.
Overlaid, you end up with:
You then use a blank <div> with the same background color as the background color of your webpage and overlay that to cover the extra bar on the first graph, but leaving enough of the first graph's background and grid-lines to extend a bit past the last bar of the second graph.
You will end up with:
You can see a working solution at at JSFiddle using jqPlot 1.0.8r1250.
Comparing the original request vs. the final version of the graph produced using this method you can see that they are very close:
Between the two the most noticeable difference is the larger space between the Y-axis in the jqPlot version. Unfortunately, there does not appear to be an option to reduce that amount for stacked bar charts.
Note that the lack of a border on the right of the graph this code produces is intentional because it did not exist in the original request. Personally, I prefer having a border on the right side of the graph. If you change the CSS a bit, that is easy to obtain:
My preferred version of the graph includes a border on the left and balances the whitespace:
You can see a working JSFiddle of this version.
All-in-all it is not that difficult. It would, of course, be easier if jqPlot supported multiple sets of bars. Hopefully it will at some point. However, the last release was 2013-03-27 and there does not appear to have been any development work after that time. Prior to that there were releases every few months. But, jqPlot is released under the GPL and MIT licenses so anyone could continue the work.
$(document).ready(function () {
//Numbers derived from desired image
//var s1 = [10, 29, 35, 48, 0];
//var s2 = [34, 24, 15, 20, 0];
//var s3 = [18, 19, 26, 52, 0];
//Scale to get 30 max on plot
var s1 = [2, 5.8, 7, 9.6, 0];
var s2 = [6.8, 4.8, 3, 4, 0];
var s3 = [13.6, 8.8, 3, 7.8, 0];
plot4 = $.jqplot('chart4', [s1, s2, s3], {
// Tell the plot to stack the bars.
stackSeries: true,
captureRightClick: true,
seriesColors: ["#1B95D9", "#A5BC4E", "#E48701"],
seriesDefaults: {
shadow: false,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
// jqPlot does not actually obey these except barWidth.
barPadding: 0,
barMargin: 66,
barWidth: 38,
// Highlight bars when mouse button pressed.
// Disables default highlighting on mouse over.
highlightMouseDown: false
},
title: {
text: '', // title for the plot,
show: false,
},
markerOptions: {
show: false, // wether to show data point markers.
},
pointLabels: {
show: false
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
tickOptions: {
show: false
},
lastPropertyConvenience: 0
},
yaxis: {
// Don't pad out the bottom of the data range. By default,
// axes scaled as if data extended 10% above and below the
// actual range to prevent data points right on grid boundaries.
// Don't want to do that here.
padMin: 0
}
},
legend: {
show: false,
location: 'e',
placement: 'outside'
},
grid: {
drawGridLines: true, // wether to draw lines across the grid or not.
shadow: false, // no shadow
borderWidth: 1,
background: 'white', // CSS color spec for background color of grid.
lastPropertyConvenience: 0
},
lastPropertyConvenience: 0
});
});
$(document).ready(function () {
//Numbers derived from desired image
//var s1 = [10, 29, 35, 48, 0];
//var s2 = [34, 24, 15, 20, 0];
//var s3 = [18, 19, 26, 52, 0];
//Scale to get 30 max on plot
var s1 = [2, 5.8, 7, 9.6, 0];
var s2 = [6.8, 4.8, 3, 4, 0];
var s3 = [3.6, 3.8, 5.2, 10.4, 0];
plot4 = $.jqplot('chart5', [s1, s2, s3], {
// Tell the plot to stack the bars.
stackSeries: true,
captureRightClick: true,
seriesColors: ["#754DE9", "#666666", "#000000"],
seriesDefaults: {
shadow: false,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
// jqPlot does not obey these options except barWidth.
show: true,
barPadding: 0,
barMargin: 66,
barWidth: 38,
// Highlight bars when mouse button pressed.
// Disables default highlighting on mouse over.
highlightMouseDown: false
},
title: {
text: '', // title for the plot,
show: false,
},
markerOptions: {
show: false, // wether to show data point markers.
},
pointLabels: {
show: false
}
},
axesDefaults: {
//show: false
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
tickOptions: {
show: false
},
lastPropertyConvenience: 0
},
yaxis: {
show: false,
// Don't pad out the bottom of the data range. By default,
// axes scaled as if data extended 10% above and below the
// actual range to prevent data points right on grid boundaries.
// Don't want to do that here.
padMin: 0,
tickOptions: {
show: false
},
}
},
legend: {
show: false,
location: 'e',
placement: 'outside'
},
grid: {
drawGridLines: false, // wether to draw lines across the grid or not.
shadow: false, // no shadow
borderWidth: 10,
background: 'transparent', // CSS color for background color of grid.
gridLineColor: 'transparent', // *Color of the grid lines.
borderColor: 'transparent', // CSS color for border around grid.
lastPropertyConvenience: 0
},
lastPropertyConvenience: 0
});
});
#cover1 {
padding:0;
margin: 0;
background-color: white;
left: 451px;
width: 88px;
/* Uncomment the next three lines to have a border on the right of the graph and
balanced whitespace:*/
/*
border-left: 2px solid #CCCCCC;
left:476px;
width: 62px;
*/
}
#chart4 .jqplot-xaxis-tick {
visibility: hidden;
}
#chart5 .jqplot-xaxis-tick {
visibility: hidden;
}
#chart4 .jqplot-yaxis-tick {
font: 9px arial
}
<link class="include" rel="stylesheet" type="text/css" href="http://cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.css" />
<!--[if lt IE 9]><script language="javascript" type="text/javascript" src="http://cdn.jsdelivr.net/excanvas/r3/excanvas.js"></script><![endif]-->
<script class="include" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Main jqPlot -->
<script class="include" type="text/javascript" src="http://cdn.jsdelivr.net/jqplot/1.0.8/jquery.jqplot.js"></script>
<!-- Additional jqPlot plugins -->
<script class="include" type="text/javascript" src="http://cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.barRenderer.min.js"></script>
<script class="include" type="text/javascript" src="http://cdn.jsdelivr.net/jqplot/1.0.8/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<div style="position:absolute; left:10px; top:10px;">
<div id="chart4" style="width:548px; height:185px;"></div>
<div id="chart5" style="width:536px; height:185px; top:-185px; left:53px;"></div>
<div id="cover1" style="position: relative; height: 152px; top:-361px;"></div>
</div>
The above code is based on that at the example page listed in the question.
Practical solution...
$(document).ready(function(){
var s1 = [2, 0, 0, 10,11,0, 6, 2, 0,10,11];
var s2 = [7, 0, 0, 4,11,0, 6, 2, 0,10,11];
var s3 = [4, 0, 0, 7,11,0, 6, 2, 0,10,11];
var s4 = [0, 20, 0, 0,0,0, 0, 0, 0,0,0];
plot3 = $.jqplot('chart3', [s1, s2, s3,s4], {
stackSeries: true,
captureRightClick: true,
seriesDefaults:{
renderer:$.jqplot.BarRenderer,
rendererOptions: {
barMargin: 30,
highlightMouseDown: true
},
pointLabels: {show: true}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
},
yaxis: {
padMin: 0
}
},
legend: {
show: true,
location: 'e',
placement: 'outside'
}
});
$('#chart3').bind('jqplotDataClick',
function (ev, seriesIndex, pointIndex, data) {
$('#info3').html('series: '+seriesIndex+', point: '+pointIndex+', data: '+data);
}
);
});
Image:

Resources