This is my HTML page:
<div>
<canvas id="chart-area1" width="300" height="300"/>
</div>
<script src="Chart.js"></script>
<script>
var pieData1 = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
window.onload = function(){
var ctx1 = document.getElementById("chart-area1").getContext("2d");
var myPie1 = new Chart(ctx1).Pie(pieData1);
};
</script>
<div>
<canvas id="chart-area2" width="300" height="300"/>
</div>
<script src="Chart1.js"></script>
<script>
var pieData2 = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
window.onload = function(){
var ctx2 = document.getElementById("chart-area2").getContext("2d");
var myPie2 = new Chart(ctx2).Pie(pieData2);
};
</script>
'Chart.js' and 'Chart1.js' contains same content. I used 'Chart.js' only once but it didn't work. So I tried with two.
The above HTML page is displaying only one pie chart. The other pie chart is not displayed but occupying the space in the page.
What changes should be made so that two pie charts can be displayed?
Thanks in advance.
You set window.onload to a value twice, causing it to be overwritten with the latest value:
window.onload = function(){
var ctx1 = document.getElementById("chart-area1").getContext("2d");
var myPie1 = new Chart(ctx1).Pie(pieData1);
};
// ...
window.onload = function(){
var ctx2 = document.getElementById("chart-area2").getContext("2d");
var myPie2 = new Chart(ctx2).Pie(pieData2);
};
Why not combine the two functions?
Like:
var func1 = function() { /* set up chart 1 */ },
func2 = function() { /* set up chart 2 */ };
window.onload = function() {
func1();
func2();
};
The problem is that you reassign window.onload so it only loads the second one. Try doing this instead:
window.onload = function(){
var ctx1 = document.getElementById("chart-area1").getContext("2d");
var myPie1 = new Chart(ctx1).Pie(pieData1);
var ctx2 = document.getElementById("chart-area2").getContext("2d");
var myPie2 = new Chart(ctx2).Pie(pieData2);
};
Here is the code for the pichat which worked for me.
<link href="../JSfiles/Style.css" rel="stylesheet" />
<script src="../ChartsJs/Chart.js"></script>
<script src="../ChartsJs/Chart.min.js"></script>
<script src="../ChartsJs/jquery-1.7.1.min.js"></script>
<script src="http://www.chartjs.org/assets/Chart.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'PubPerformancePichat.aspx/GetDataonload',
data: {},
success: function (response) {
drawchart(response.d); // calling method
},
error: function () {
//alert("Error:Something went wrong.Contact the Adminstrator");
//alert(response);
}
})
});
function drawchart(dataValues) {
var arr = [];
var arrcolor = '#231F20, #FFC200, #F44937, #16F27E, #FC9775, #5A69A6';
var acolor = arrcolor.split(',');
for (var i = 0; i < dataValues.length; i++) {
var obj = {};
obj.color = acolor[i];
obj.value = dataValues[i].Accountvalues;
obj.label = dataValues[i].Accounts;
arr.push(obj);
}
// Instantiate and draw our chart, passing in some options
var ctx = $("#myChart").get(0).getContext("2d");
var myPieChart = new Chart(ctx).Pie(arr);
}
</script>
---here is the CS File
[WebMethod(EnableSession = true)]
public static List<Chatdata> GetDataonload()
{
List<Chatdata> dataList = new List<Chatdata>();
using (SqlConnection con = new SqlConnection("Data Source=203.115.195.52;Initial Catalog=mcom_ad_engine;Persist Security Info=True;User ID=appl;Password=mcom007;"))
{
string publisherid = "2000105";
if (!string.IsNullOrEmpty(publisherid))
{
//string StartDate = DateTime.Now.AddDays(-180).ToString("yyyy-MM-dd");
string StartDate = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd");
string EndDate = DateTime.Now.ToString("yyyy-MM-dd");
SqlCommand cmd = new SqlCommand("Sp_publisher_Totalunpaied_pichart", con);
cmd.CommandTimeout = 50;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#publisherid", publisherid);
cmd.Parameters.AddWithValue("#istartdate", StartDate);
cmd.Parameters.AddWithValue("#ienddate", EndDate);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
foreach (DataRow dtrow in dt.Rows)
{
if (dtrow[0].ToString() != "Total Earned")
{
Chatdata details = new Chatdata();
details.Accounts = dtrow[0].ToString();
// details.spent = Convert.ToInt64(dtrow[2].ToString());
if (dtrow[1].ToString().StartsWith("-"))
{
string bal = dtrow[1].ToString();
bal = bal.Substring(1, bal.Length - 1);
details.Accountvalues = Convert.ToInt64(bal);
}
else
{
details.Accountvalues = Convert.ToInt64(dtrow[1].ToString());
}
dataList.Add(details);
}
}
}
else
{
//navigate to Login Page
}
return dataList;
}
}
Related
I'm using List to load radar chart from controller.
How can i load dynamic labels and data for that chart from controller.
List<MyModel> modelIist = new List<MyModel>();
MyModel model = new MyModel();
model.Data = 1;
model.Label = "First";
modelIist.Add(model);
model = new MyModel();
model.Data = 2;
model.Label = "Second";
modelIist.Add(model);
model = new MyModel();
model.Data = 3;
model.Label = "Third ";
modelIist.Add(model);
ViewBag.radarDesc = modelIist;
I'm loading data above from above list.
<script>
$(document).ready(function () {
var ctx = $("#chart-line");
var myLineChart = new Chart(ctx, {
type: 'radar',
data: {
labels: [], //want to load from the list
/*},*/
datasets: [{
data: [],//want to load from the list
label: "MyData",
borderColor: "#458af7",
backgroundColor: '#458af7',
fill: true
}]
},
options: {
title: {
display: true,
text: '(Max points - 300)'
}
}
});
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.bundle.min.js"></script>
<canvas id="chart-line" width="299" height="200" class="chartjs-render-monitor" style="display: block; width: 299px; height: 200px;"></canvas>
How can load label: [], data:[] from mvc.
Try this way:
Install Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet Package and then serialize the ViewBag.radarDesc into a valid JavaScript array:
ViewBag.radarDesc = Newtonsoft.Json.JsonConvert.SerializeObject(modelIist);
Then take out the Label and Data in the Page and fill it to the appropriate position:
$(document).ready(function () {
var Label = [];
var Data = [];
var radarDesc = #Html.Raw(#ViewBag.radarDesc);
$.each(radarDesc, function (index, value) {
Label.push(value.Label);
Data.push(value.Data);
});
var ctx = $("#chart-line");
var myLineChart = new Chart(ctx, {
type: 'radar',
data: {
labels: Label, //want to load from the list
/*},*/
datasets: [{
data: Data,//want to load from the list
label: "MyData",
borderColor: "#458af7",
backgroundColor: '#458af7',
fill: true
}]
},
options: {
title: {
display: true,
text: '(Max points - 300)'
}
}
});
});
Test Result:
I have a project where I created the backend with flask. It reads the data from the csv file and transfers it to html. It reads data every second with Ajax. Then I visualize the data with plotly.js. With Ajax, every get operation comes with a delay.I am working with approximately 2000 data.
However, there is a delay in my code. How can I refactor this code? What can I do to avoid delay?
$(function requestData() {
$.ajax({
type: "GET",
url: "/deneme3",
success: function (data) {
//console.log('success',data);
//console.log('success',data[0]);
//console.log('success',data[1]);
var enlem = [];
var boylam = [];
var ch1 = [];
var ch2 = [];
var ch3 = [];
var ch4 = [];
enlem = data[0];
boylam = data[1];
ch1 = data[2];
ch2 = data[3];
ch3 = data[4];
ch4 = data[5];
//console.log('enlem',enlem);
//console.log('boylam',boylam);
var trace1 = {
x: enlem,
y: boylam,
mode: "markers",
marker: {
size: 10,
color: ch1,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
};
var data = [trace1];
var layout = {
title: "Scatter Plot with a Color Dimension",
};
Plotly.newPlot("tester", data, layout);
setInterval(function () {
var update = {
x: [[enlem]],
y: [[boylam]],
};
Plotly.extendTraces("tester", update, [0]);
}, 100);
//ch1 grafik
var trace2 = {
y: ch1,
type: "scatter",
};
var data2 = [trace2];
var layout2 = {
title: "CH1",
};
Plotly.newPlot("ch1", data2, layout2);
setInterval(function () {
var update = {
y: [[ch1]],
};
Plotly.extendTraces("ch1", update, [0]);
}, 100);
//ch2 grafik
var trace3 = {
y: ch2,
type: "scatter",
};
var data3 = [trace3];
var layout3 = {
title: "CH2",
};
Plotly.newPlot("ch2", data3, layout3);
setInterval(function () {
var update = {
y: [[ch2]],
};
Plotly.extendTraces("ch2", update, [0]);
}, 100);
//ch3 grafik
var trace4 = {
y: ch3,
type: "scatter",
};
var data4 = [trace4];
var layout4 = {
title: "CH3",
};
Plotly.newPlot("ch3", data4, layout4);
setInterval(function () {
var update = {
y: [[ch3]],
};
Plotly.extendTraces("ch3", update, [0]);
}, 100);
//ch4 grafik
var trace5 = {
y: ch4,
type: "scatter",
};
var data5 = [trace5];
var layout5 = {
title: "CH4",
};
Plotly.newPlot("ch4", data5, layout5);
setInterval(function () {
var update = {
y: [[ch4]],
};
Plotly.extendTraces("ch4", update, [0]);
}, 100);
},
});
setTimeout(requestData, 100);
});
Also, which of the Ajax and socketio would it make more sense to use?
As discussed in the comments, something like this might work: initialize empty plots, then just fill in data in the update function:
function plotData(data) {
const [enlem, boylam, ...chs] = data;
Plotly.extendTraces("tester", {
x: [[enlem]],
y: [[boylam]],
}, [0]);
for (let i = 0; i < 4; i++) {
const j = i + 1;
Plotly.extendTraces(`ch${j}`, {
y: [[chs[i]]],
}, [0]);
}
// After success, wait before loading more data
setTimeout(requestData, 1000);
}
function requestData() {
// Simulate a successful response that returns 6 numbers.
plotData([Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random()]);
// If a real endpoint was available, you could do something like
/*$.ajax({
type: "GET",
url: "/deneme3",
success: plotData,
});*/
}
function initialize() {
Plotly.newPlot("tester", [{
x: [],
y: [],
mode: "markers",
marker: {
size: 10,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
}], {
title: "Scatter Plot with a Color Dimension",
});
for (let i = 1; i <= 4; i++) {
Plotly.newPlot(`ch${i}`, [{
y: [],
type: "scatter",
}], {
title: `CH${i}`,
});
}
requestData(); // Fire off first update
}
$(initialize);
div {
width: 33%;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js" charset="utf-8"></script>
<div id="tester"></div>
<div id="ch1"></div>
<div id="ch2"></div>
<div id="ch3"></div>
<div id="ch4"></div>
My chart is not shown on browser screen. I am using chart.js with meteor and also trying to do it with onRendered or onCreated but it didn't work for me.
Here is my code
<div class="pie-canvas">
<canvas id="myChart" width="350" height="350"></canvas>
</div>
Js file ->
Template.home.rendered = function() {
Deps.autorun(function() { drawChart(); });
};
function drawChart() {
var oldCount = 2;
var newCount = 4;
var data = [{
value: newCount,
color: "#e53935",
highlight: "#c62828",
label: "New"
}, {
value: oldCount,
color: "#3949ab",
highlight: "#1a237e",
label: "Regular"
}];
var pieOptions = {
animation: false,
}
if ($("#myChart").get(0)) {
var ctx = $("#myChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
new Chart(ctx).Pie(data, pieOptions);
}
}
home is my template name
When you console log '$("#myChart").get(0)' this will return you undefined, because on rendered your get(0) is not initialized, For prevent this you have to add a callback when you initialized you chart. So your get(0) will be initialized first then you can create your chats.
'$("#myChart").get(0)' is not a reative thing so your view will be not re-initialized.
Here is the working code:
function drawChart() {
var oldCount = 2;
var newCount = 4;
var data = [{
value: newCount,
color: "#e53935",
highlight: "#c62828",
label: "New"
}, {
value: oldCount,
color: "#3949ab",
highlight: "#1a237e",
label: "Regular"
}];
var pieOptions = {
animation: false,
}
// Added a callback here.
setTimeout( function(){
if ($("#myChart").get(0)) {
var ctx = $("#myChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx);
console.log(myNewChart);
new Chart(ctx).Pie(data, pieOptions);
}
})
}
I am using a doughnut chart plugin in my website. It is working fine but I want multiple chart on same page with different data. Please see the code below.
This is the chart I am using
<canvas id="chart-area1" width="200" height="200" style="width:150px !important; height:150px !important;"/></canvas>
Script is here
<script src="http://www.chartjs.org/assets/Chart.min.js"></script>
<script>
var doughnutData = [
{
value: 45,
color:"#17CB8A",
highlight: "#17CB8C",
label: "Strating"
},
{
value: 12,
color: "#FF003C",
highlight: "#FF003A",
label: "Warning"
},
{
value: 7,
color: "#fb6800",
highlight: "#fb6801",
label: "Past Due"
},
{
value: 9,
color: "#88c100",
highlight: "#88c102",
label: "In Progress"
},
];
window.onload = function(){
var ctx = document.getElementById("chart-area1").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
};
</script>
How I can copy this chart with different attributes?
This is how i did it. with multiple canvases.
<script>
var doughnutData = [ ... ];
var doughnutData2 = [ ... ];
var doughnutData3 = [ ... ];
window.onload = function(){
var ctx = document.getElementById("chart-area1").getContext("2d");
var dtx = document.getElementById("chart-area2").getContext("2d");
var etx = document.getElementById("chart-area3").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
window.myDoughnut2 = new Chart(dtx).Doughnut(doughnutData2, {responsive : true});
window.myDoughnut3 = new Chart(etx).Doughnut(doughnutData3, {responsive : true});
};
</script>
If you want to use multiple Charts on same canvas you can use the fork FVANCOP did for Chart.js here
Im populating each Titanium.UI.createTableViewRow from a json file, and I wonder how I can add a label (Titanium.UI.createLabel) to each created Titanium.UI.createTableViewRow and center all outputed text?
I have created a Titanium.UI.createLabel, but how to add my Label to each created Titanium.UI.createTableViewRow, and center all text?
This is a created Label:
var wrapperLabel = Titanium.UI.createLabel({
text: 'Signed:',
color: '#ffffff',
textAlign:'center',
font: {
fontWeight: 'bold',
fontSize: 22
},
height:'auto'
});
win3.add(wrapperLabel);
var view = Titanium.UI.createTableView({
maxRowHeight:40,
minRowHeight:30,
height: Titanium.UI.SIZE,
width: Titanium.UI.FILL,
color: 'black'
});
win3.add(view);
xhr.onload = function() {
var data = [];
var objects = JSON.parse(this.responseText);
for (s in objects) {
data.push(Titanium.UI.createTableViewRow({
title: objects[s]
}));
data.push(Titanium.UI.createTableViewRow({
title: objects[s].New
}));
data.push(Titanium.UI.createTableViewRow({
title: objects[s].Signed
}));
data.push(Titanium.UI.createTableViewRow({
title: objects[s].Returned
}));
}
view.data = data;
};
Something like this:
for (s in objects) {
var label = Ti.UI.createLabel (_properties_);
var row = Ti.UI.createTableViewRow(_propeties_);
row.add(label);
data.push(row);
}
try this one...
var row_propetiy = {
height : "40dp"
};
var lbl_propetiy = {
color: '#000',
textAlign:'center',
font: {
fontWeight: 'bold',
fontSize: '22dp'
},
height:Ti.UI.FILL
};
xhr.onload = function() {
var data = [];
var objects = JSON.parse(this.responseText);
for (s in objects) {
var row = Ti.UI.createTableViewRow(row_propetiy);
var lbl = Ti.UI.createLable(lbl_propetiy);
lbl.text = objects[s];
row.add(lbl);
data.push(row);
}
view.data = data;
};