c3.js with json ,split line line - c3.js

I have a JSON array and want to make a chart with C3.js. My example gives me only one line. I want to display however one line for every user. How can I achieve this?
Here is my code:
this.chart = c3.generate({
data: {
json: [
{
ExamID: 'Exam1',
result: 80,
user:"user1"
},
{
ExamID: 'Exam2',
result: 90,
user:"user1"
},
{
ExamID: 'Exam1',
result: 70,
user:"user2"
},
{
ExamID: 'Exam2',
result: 60,
user:"user2"
}
],
keys: {
x: 'ExamID',
value: ['result'],
},
},
axis: {
x: {
type: 'category',
}
}
});

You need to have a different JSON structure. Every object in the array (every exam) needs to have the results of all students in it. You can use a key for every student and rename the key for the legend with the attribute names. Here is a Fiddle: https://jsfiddle.net/b5pd3wn6/
var chart = c3.generate({
bindto: "#element",
data: {
json: [
{
ExamID: 'Exam1',
user1: 80,
user2: 50
}, {
ExamID: 'Exam2',
user1: 90,
user2: 40
}
],
keys: {
x: 'ExamID',
value: ['user1', 'user2']
},
names: {
'user1': 'Peter Miller',
'user2': 'Vladimir Peterhans'
}
},
axis: {
x: {
type: 'category'
}
}
});

Related

ChartJS: How to center monthly bars against a daily line chart?

I'm trying to display total monthly sales and daily stock level. This way you could easily see that you didn't have any sales a particular month because you had low stock. Monthly sales is a bar chart that should be in the center of each month (in between the ticks).
In order to get it close to the middle my data is using the 15th of each month as the date to center it. I would want to know if there is a better way to achieve this?
JSFiddle to play around with: https://jsfiddle.net/8Lydhpqc/3/
const dailyStock = [
{ x: "2017-08-02", y: 1 },
{ x: "2017-08-25", y: 3 },
{ x: "2017-09-10", y: 7 },
{ x: "2017-09-28", y: 0 },
{ x: "2017-10-02", y: 3 },
{ x: "2017-10-24", y: 2 },
{ x: "2017-11-01", y: 1 },
{ x: "2017-11-30", y: 0 },
];
//using the 15th of each month to center it
const monthlyTotal = [
{ x: "2017-08-15", y: 1 },
{ x: "2017-09-15", y: 10 },
{ x: "2017-10-15", y: 5 },
{ x: "2017-11-15", y: 5 },
];
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["2017-08", "2017-09", "2017-10", "2017-11"],
datasets: [
{
label: "sales",
data: data,
backgroundColor: "green",
borderColor: "black",
borderWidth: 1,
order: 2,
},
{
label: "stock",
type: "line",
data: dailyStock,
backgroundColor: "orange",
borderColor: "orange",
fill: false,
order: 1,
},
],
},
options: {
scales: {
xAxes: [
{
type: "time",
time: {
unit: "month",
displayFormats: {
month: "MMM",
},
},
distribution: "linear",
},
],
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});
Welcome to Stackoverflow!
It seems that there is a way better than using the 15th of the month.
You need to add another axis for the bar that is a category type axis. Also its pretty critical that you have "offset: true" on that axis as well. Otherwise it will not center.
In the code below I named that category "bar" and the existing one "line"
I also created a fiddle: https://jsfiddle.net/jyf8ax3e/
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["2017-08", "2017-09", "2017-10", "2017-11"],
datasets: [
{
barPercentage: .7,
xAxisID: "bar",
label: "sales",
data: monthlyTotal,
backgroundColor: "green",
borderColor: "black",
borderWidth: 1,
width: 55,
order: 2,
},
{
label: "stock",
type: "line",
data: dailyStock,
backgroundColor: "orange",
borderColor: "orange",
fill: false,
order: 1,
},
],
},
options: {
scales: {
xAxes: [
{
id: "line",
type: "time",
time: {
unit: "month",
displayFormats: {
month: "MMM",
},
},
distribution: "linear",
},
{
id: "bar",
offset: true,
type: "category",
distribution: "series",
}
],
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
},
});

Set the y axis spacing in c3

I have the following chart and I want to make the y axis spacing integers only (when the data to display is low, I get decimals: 0.1, 0.2...). Anyone can help?
var Presence = c3.generate({
bindto: '#presence',
data: {
url: 'ranking.csv',
x:'AC_YEAR',
types: {
Number_students: "bar",
Ranking: 'spline'
},
axes:{
Number_students: "y",
Ranking: "y2"
}
},
axis: {
y: {
label: {
text:"Students",
position: "outer-middle"
},
tick: {
outer: false}
},
y2: {
inverted:true,
show: true,
label: {
text:"Ranking position",
position: "outer-middle"
},
tick: {
outer: false
}
},
x: {
label: {
text:"Year",
position: "outer-center"
},
tick: {outer: false}
}
},
size: {
height: 400,
width: 800
},
});
The csv file looks like this:
AC_YEAR,Number_students,Ranking
2011,1,103
2012,2,30
2014,1,178
2015,1,188
But the csv is changing over time and sometimes the Number of students is 100. So that is why I do not want to fix values on the y axis, only avoid having floats when the Number of students is low (1 or 2)
Thanks in advance!
Set the y tick formatting function to return blanks on non-whole numbers
y: {
label: {
text:"Students",
position: "outer-middle"
},
tick: {
format: function (d) {
return Math.abs(Math.round(d) - d) < 0.001 ? d : "";
},
outer: false
}
},

Multiple sort on Kendo Grid columns / DataSource - set sorting dynamically

What I'm trying to accomplish is to apply an "automatic" secondary column sort when a user sorts a column in a kendo grid.
So in this JS fiddle example, if a user sorts by "Value", it'll also sort by "Name". Note that the 0s are sorted together, but the names aren't alphabetical. I'd like them to be alphabetical (the secondary sort).
Here's an attempt at overriding the datasource sorting to accomplish this. I'm taking the user's original sort and the adding an additional sort on "SortedName". Based on the sorting array that's logged, it seems to be close but is still not working.
Any other ideas on how to accomplish this?
Note: I don't want to allow users to sort by multiple columns. The real world example I'm using this for can have up to 50+ columns (unfortunately), so multiple sort can get confusing / unintuitive. And I'd like it to be done behind the scenes without extra user interaction.
Example code for overriding kendo datasource sort():
dataSource.originalSort = dataSource.sort;
dataSource.sort = function () {
// take the user's sort and apply sorting on an additional column
// the sort array should look like this:
[
{ field: "Value", dir: "asc" }, // this is what the user sorted by
{ field: "SortedName", dir: "asc" }, // and I'm adding this
]
return dataSource.originalSort.apply(this, arguments);
}
Please try with the below code snippet.
<div id="grid">
</div>
<script>
var dataSource = new kendo.data.DataSource({
data: [
{ Name: "Lisa", Value: 1 },
{ Name: "Dan", Value: 12 },
{ Name: "Ken", Value: 5 },
{ Name: "Arthur", Value: 15 },
{ Name: "Bob", Value: 0 },
{ Name: "Sally", Value: 0 },
{ Name: "Alexis", Value: 0 },
{ Name: "Cody", Value: 0 },
{ Name: "Steve", Value: 0 },
{ Name: "Andrew", Value: 0 },
{ Name: "Duke", Value: 0 }
],
schema: {
model: {
fields: {
Name: { type: "string" },
Value: { type: "number" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
dataBound: function (e) {
var isSortedByName = false;
var grid = $("#grid").data("kendoGrid");
var ds = grid.dataSource;
var sort = ds.sort();
if (sort) {
for (var i = 0; i < sort.length; i++) {
if (sort[i].field == "Name") {
isSortedByName = true;
}
}
if (isSortedByName == false) {
sort.push({ field: "Name", dir: "asc" });
ds.sort(sort);
}
}
},
columns: [
{ field: "Name" },
{ field: "Value" }
],
sortable: true
});
</script>

c3.js how to remove line with tooltip?

I am creating a line chart using c3.js. I want to remove the default indicator line to x-axis with the tooltip.
I have tried tooltip formatting but the line remains same.
How this can be done?
grid:{
focus:{
show:false
}
}
May be at that time when person answer this question config parameter not provided but now you can do it through above mention configuration. Reference http://c3js.org/reference.html#grid-focus-show
Example code below
var chart = c3.generate({
data: {
columns: [
['data1', 30, 200, 100, 400, 150, 250],
['data2', 50, 20, 10, 40, 15, 25]
]
},
grid:{
focus:{
show:false
}
}
});
Just override the following css property in .c3-xgrid-focus class:-
.c3-grid .c3-xgrid-focus {
visibility : hidden !important;
}
I could not quickly find a config parameter to turn this feature off in the api doc.
point: {
show: false
},
False to hide the points and true for show the points
Note:
Make sure that you are going to write this after the loading the data and along with your other settings in c3 Generate function
Here is the Example:
http://c3js.org/reference.html#point-show
In below code I have highlighted the code with a comment:
var chart = c3.generate({
bindto: '#CYCLE_CHART',
data: {
columns: [
["Cycletime"].concat(objCycle.cData), ["Downtime"].concat(objDowntime.dData), ["StdCycletime"].concat(objStdCycle.stdCData), ["StdLoadunloadtime"].concat(objStdLUtime.stdLUData),
],
type: 'spline',
types: {
Cycletime: 'bar',
Downtime: 'bar'
},
names: {
Cycletime: 'Cycle time',
Downtime: 'Load time',
StdCycletime: 'Std Cycle time',
StdLoadunloadtime: 'Std Load time'
},
},
axis: {
x: {
label: {
text: 'Cycles',
position: 'outer-center'
},
max: 10,
min: 1,
},
y: {
label: {
text: 'Seconds',
position: 'outer-middle'
},
max: Y_axis,
min: 1,
}
},
// Here!
point: {
show: false
},
tooltip: {
show: true
}
});
According to BonifatiusK´s comment, you should hide them by editing the chartOptions.
{
tooltip: {
show: false
}
}
Overriding CSS properties of c3 is not a good idea.

c3.js: Remove categories from x-axis

I've spent a lot of time with c3's documentation and examples, but have not been able to find a a way to unload or hide a category from a chart using API functions. Removing lines or bars is easy, but removing x-axis categories is proving more challenging. Here is a streamlined version of my chart.
var genderChart = c3.generate({
bindto: '#chart-gender',
data: {
json: [
{
Disease:"Mumps",
"Female":231,
"Male":198
},
Disease:"Tuberculosis",
"Female":18,
"Male":197
}
],
type: 'bar',
keys: {
x: "Disease",
value: ["Female","Male"]
},
selection: {
enabled: true,
grouped: true
},
},
axis: {
x: {
type: 'category',
}
},
});
I would like to dynamically show and hide (load and unload) diseases. For instance, I would like to be able to toggle Tuberculosis on and off. My actual chart has a number of other diseases. If I structured the data such that the diseases were bars and gender was on the x-axis, this would be easy. However, that is not comparison I wish to show with this chart. Is this possible with c3? How do I select all of the values with a given x value (disease) and then unload those data points? I appreciate any insight.
I would build up the json data object and then re-render the chart.
Here's an example:
var data = [{
Disease: "Mumps",
Female: 231,
Male: 198
}, {
Disease: "Tuberculosis",
Female: 18,
Male: 197
}];
$("button").click(function () {
Render();
});
Render()
function Render() {
var selectedData = [];
if ($("#mumps").prop("checked")) selectedData.push(data[0]);
if ($("#tb").prop("checked")) selectedData.push(data[1]);
var genderChart = c3.generate({
data: {
json: selectedData,
type: 'bar',
keys: {
x: "Disease",
value: ["Female", "Male"]
},
selection: {
enabled: true,
grouped: true
},
},
axis: {
x: {
type: 'category',
}
},
});
}
Here's the code in a fiddle:
http://jsfiddle.net/ot19Lyt8/14/

Resources