Show values on google piechart legends - asp.net

I have this google piechart, which is working fine, except on the legend text along with it, I wanna show the percentage and numbers. The below would be the code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'Registration',
legend: { position: 'right', textStyle: { color: 'blue', fontSize: 16 } }
};
$.ajax({
type: "POST",
url: "adminrep.aspx/GetChartData",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 900px; height: 500px; margin-top:60px;"></div>
How do I get this done? Thanks in advance.

Try using .setFormattedValue to format the the labels in the DataTable.
This still requires you do a little bit of manual calculation for the getting the total sum of values, but it should work:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var options = {
title: 'Registration',
legend: {
position: 'right',
textStyle: { color: 'blue', fontSize: 16 }
}
};
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
json: JSON.stringify({
d: [
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]})
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var data = google.visualization.arrayToDataTable(r.d);
var count = data.getNumberOfRows();
var values = Array(count).fill().map(function(v, i) {
return data.getValue(i, 1);
});
var total = google.visualization.data.sum(values);
values.forEach(function(v, i) {
var key = data.getValue(i, 0);
var val = data.getValue(i, 1);
data.setFormattedValue(i, 0, key + ' (' + (val/total * 100).toFixed(1) + '%)');
});
var chart = new google.visualization.PieChart($("#chart")[0]);
chart.draw(data, options);
},
failure: function (r) {
alert(r.d);
},
error: function (r) {
alert(r.d);
}
});
}
</script>
<div id="chart" style="width: 900px; height: 500px; margin-top:60px;"></div>
Example: https://jsfiddle.net/cn74tvmL/show

You need to use number format:
var formatter = new google.visualization.NumberFormat({pattern: '#,### MW'});
formatter.format(data, 1);
or:
chart1.options = {
.
.
.
pieSliceText: 'value',
legend: {
position: 'labeled',
labeledValueText: 'both',
textStyle: {
color: 'blue',
fontSize: 14
}
}
};

Related

Draw chart.js with data from server

I know I must be doing a basic mistake but I am new to this. I would like to populate a line chart (chart.js) in my View with data from the server. I have confirmed that the data is received in the View but I suspect that it is in a wrong format.
My Controller:
public ActionResult GetLineChartData()
{
var data = new
{
title = "test_data",
data = new[] {
new { value = "V1", key = "11"},
new{ value = "V2", key = "10"}
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
On my View:
<canvas id="lineChart" width="400" height="400"></canvas>
<button id="lineChartUpdate">Update Chart</button>
<script>
$(document).ready(function () {
$("#lineChartUpdate").click(function () {
$.ajax({
type: "Post",
url: '#Url.Action("GetLineChartData", "Posts")',
data: {},
dataType: "json",
traditional: true,
success: function (data) {
new Chart('lineChart', {
type: 'line',
data: {
labels: data.data.map(a => a[0]),
datasets: [{
label: 'My Dataset',
data: data.data.map(a => a[1]),
fill: false,
borderColor: 'red'
}]
},
options: {
scales: {yAxes: [{ ticks: { beginAtZero: true } }]}
}
});
}
});
});
});
</script>
I am getting this error: "Invalid scale configuration for scale: yAxes"
This is because it is invalid as the errors says, you are using V2 config with V3.
In V3 all scales are there own object in the scales object instead of 2 arrays.
Changing to:
scales: {
y: {
// Scale config
}
}
Will remove the warning and make the config apply correctly
For all changes between V2 and V3 please read the migration guide

Wp-Fullcalendar not showing up

i´m still searching for an answer why my calendar is not showing up...
I´m workin on an multisite WordPress and want to implement WP-Fullcalendar but i think i do something wrong.
I think when you´re looking into my code you´ll perhaps laught but i dont know the anser why my calendar don´t show.
Thank you for your help! Greetings
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/moment.min.js'></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery.min.js'></script>
<script src="http://fullcalendar.io/js/fullcalendar-2.1.1/lib/jquery-ui.custom.min.js"></script>
<script src='http://fullcalendar.io/js/fullcalendar-2.1.1/fullcalendar.min.js'></script>
<script>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: [
{
title: 'All Day Event',
start: '2017-04-01'
},
{
title: 'Long Event',
start: '2017-04-07',
end: '2017-04-10'
},
{
id: 999,
title: 'Repeating Event',
start: '2017-04-09T16:00:00'
},
{
id: 999,
title: 'Repeating Event',
start: '2017-04-16T16:00:00'
}
],
// Convert the allDay from string to boolean
eventRender: function(event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
var url = prompt('Type Event url, if exits:');
if (title) {
var start = $.fullCalendar.formatDate(start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: 'event.php',
data: 'title='+ title+'&start='+ start +'&end='+ end +'&url='+ url ,
type: "POST",
success: function(json) {
alert('Added Successfully');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
eventDrop: function(event, delta) {
var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: 'event.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
},
eventResize: function(event) {
var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd HH:mm:ss");
var end = $.fullCalendar.formatDate(event.end, "yyyy-MM-dd HH:mm:ss");
$.ajax({
url: 'event.php',
data: 'title='+ event.title+'&start='+ start +'&end='+ end +'&id='+ event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
}
});
});
</script>
<style>
body {
margin-top: 40px;
text-align: center;
font-size: 14px;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
}
#calendar {
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id='calendar'> ?></div>
</body>
</html>
You're loading jQuery twice. Remove one of them and it should resolve your issue.

Why highchart not show me in asp.net?

I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!

Morris chart does not display data from external URL

I have a Morris chart that I try to use that gets data from an external source in this case an aspx page. But the chart is not displayed at all. The only chart that is displayed is the one I add static data to myfirstchart.
Anyone see what I am missing?
Chart page:
<head runat="server">
<title></title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
Morris.Donut({
element: 'morris-donut-chart',
data: $.parseJSON(Graph()),
resize: true
});
});
function Graph() {
var data = "";
$.ajax({
type: 'POST',
url: 'data.aspx',
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: {},
success: function (result) {
data = result.d;
},
error: function (xhr, status, error) {
alert(error);
}
});
return data;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="morris-donut-chart" style="height: 250px;"></div>
<div id="myfirstchart" style="height: 250px;"></div>
</div>
</form>
<script>
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{ year: '2008', value: 20 },
{ year: '2009', value: 10 },
{ year: '2010', value: 5 },
{ year: '2011', value: 5 },
{ year: '2012', value: 20 }
],
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Value']
});
</script>
</body>
Data page:
protected void Page_Load(object sender, EventArgs e)
{
var sb = new StringBuilder();
sb.Append("[");
sb.Append(" { label: '2012-10-01', value: 802 },");
sb.Append(" { label: '2012-10-02', value: 783 },");
sb.Append(" { label: '2012-10-03', value: 820 },");
sb.Append(" { label: '2012-10-04', value: 839 },");
sb.Append(" { label: '2012-10-05', value: 792 },");
sb.Append(" { label: '2012-10-06', value: 859 },");
sb.Append(" { label: '2012-10-07', value: 790 },");
sb.Append("]");
var jsonSerializer = new JavaScriptSerializer();
string data = jsonSerializer.Serialize(sb.ToString());
string json = data;
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}
Use a WebMethod:
[WebMethod]
public static string getGraph()
{
List<object> json = new List<object>();
json.Add(new { label = "2012-10-01", value = 802 });
json.Add(new { label = "2012-10-02", value = 783 });
json.Add(new { label = "2012-10-03", value = 820 });
json.Add(new { label = "2012-10-04", value = 839 });
json.Add(new { label = "2012-10-05", value = 792 });
json.Add(new { label = "2012-10-06", value = 859 });
json.Add(new { label = "2012-10-07", value = 790 });
List<object> jsonObject = new List<object>();
jsonObject.Add(new {
graph = json
});
return new JavaScriptSerializer().Serialize(jsonObject); ;
}
And update your javascript with a call to the WebMethod getGraph:
$(document).ready(function () {
var graph = Graph();
Morris.Donut({
element: 'morris-donut-chart',
data: graph[0].graph,
resize: true
});
});
function Graph() {
var data = "";
$.ajax({
type: 'POST',
url: 'data.aspx/getGraph',
dataType: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: {},
success: function (result) {
data = $.parseJSON(result.d);
},
error: function (xhr, status, error) {
alert(error);
}
});
return data;
}

Generic Handler Data to Ajax Json

I have a Handler which has some data inside as shown below:
{"city1": { "name": "Adana","slug": "north-east", "url": "#", "path": "M 156.53125,407.40625 L 156.71875,408.5625 L 157.1875,407.8125 L 156.53125,407.40625 z"}}
P.S: The path is coming from SVG image. it draws a city border and there are many cities.
I try to get the data from this handler to variable to use it later...
CODE:
<script type="text/javascript">
var paths;
$.ajax({
url: '/paths.ashx',
dataType: 'json',
contentType: 'application/json',
responseType: "json",
success: function (data) {
paths = data;
alert(paths);
},
error: function (data, status, jqXHR) {
alert(status);
}
});
jQuery(function ($) {
var c = Raphael('map', "100%", "100%");
c.safari();
var label = c.popup(0, 0, "").hide();
attr = { fill: '#898989', stroke: '#FFFFFF', 'stroke-width': 2, 'stroke-linejoin': 'round' }
arr = new Array();
for (var item in paths) {
var p = c.path(paths[item].path);
arr[p.id] = item;
p.attr(attr);
p.hover(function () {
this.animate({
fill: '#8fbf27'
}, 200);
bbox = this.getBBox();
label.attr({ text: paths[arr[this.id]].name }).update(bbox.x, bbox.y + bbox.height / 2, bbox.width).toFront().show();
}, function () {
this.animate({
fill: attr.fill
}, 200);
label.hide();
})
.click(function () {
location.href = paths[arr[this.id]].url;
})
}
});
</script>
The problem comes right here...paths or data is undefined, it's always empty. But paths.ashx is not empty at all...
I couldnt find the solution...could you take a look pls...
Put your jQuery .ajax() function inside of the jQuery DOM ready function and the drawing logic inside the success handler of the AJAX call, like this:
<script type="text/javascript">
var paths;
jQuery(function ($) {
$.ajax({
url: '/paths.ashx',
dataType: 'json',
contentType: 'application/json',
responseType: "json",
success: function (data) {
paths = data;
alert(paths);
var c = Raphael('map', "100%", "100%");
c.safari();
var label = c.popup(0, 0, "").hide();
attr = { fill: '#898989', stroke: '#FFFFFF', 'stroke-width': 2, 'stroke-linejoin': 'round' }
arr = new Array();
for (var item in paths) {
var p = c.path(paths[item].path);
arr[p.id] = item;
p.attr(attr);
p.hover(function () {
this.animate({
fill: '#8fbf27'
}, 200);
bbox = this.getBBox();
label.attr({ text: paths[arr[this.id]].name }).update(bbox.x, bbox.y + bbox.height / 2, bbox.width).toFront().show();
}, function () {
this.animate({
fill: attr.fill
}, 200);
label.hide();
})
.click(function () {
location.href = paths[arr[this.id]].url;
})
}
},
error: function (data, status, jqXHR) {
alert(status);
}
});
});
You're trying to draw before the ajax promise is full filled, try this
function drawMap (paths) {
var c = Raphael('map', "100%", "100%");
c.safari();
var label = c.popup(0, 0, "").hide();
attr = { fill: '#898989', stroke: '#FFFFFF', 'stroke-width': 2, 'stroke-linejoin': 'round' }
arr = new Array();
for (var item in paths) {
var p = c.path(paths[item].path);
arr[p.id] = item;
p.attr(attr);
p.hover(function () {
this.animate({
fill: '#8fbf27'
}, 200);
bbox = this.getBBox();
label.attr({ text: paths[arr[this.id]].name }).update(bbox.x, bbox.y + bbox.height / 2, bbox.width).toFront().show();
}, function () {
this.animate({
fill: attr.fill
}, 200);
label.hide();
})
.click(function () {
location.href = paths[arr[this.id]].url;
})
}
}
and from your ajax request
$.ajax({
url: '/paths.ashx',
dataType: 'json',
contentType: 'application/json',
responseType: "json",
success: function (data) {
paths = data;
drawMap(paths); //notice this
},
error: function (data, status, jqXHR) {
alert(status);
}
});

Resources