<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">';
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Tools', 'Number'],
['example1', $countr1],
['example2', $countr2],
]);
var options = {
title: 'Available Tools',
titleTextStyle: {color: '#FFFFFF'},
backgroundColor: 'transparent',
legend: 'right',
chartArea: {'width': '100%', 'height': '80%' },
pieSliceText: 'label',
pieHole: 0.4,
colors:['#202020','#282828','#303030','#383838','#404040','#484848','#505050']
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
</script>
How to change tools text color "example1" and "example2" in this google visualization PieChart script. i want to color of exactly just "example1" and "example2"
I'm following this article to render highchart with json data from django query. However chart is not rendered but I'm not getting any errors from Django or by the client when inspecting source. Appreciate if anyone can point the mistakes. Thank you in advance.
I'm using django 2.0 and python3.5
models.py
PLATFORM = (
('ipcore','IPCORE'),
('metro','METRO E'),
('edge','EDGE'),
('access','ACCESS'),
('voice','VOICE'),
('system','SYSTEM'),
('iptv','IPTV'))
class Contract(models.Model):
vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE)
name = models.CharField(max_length=500)
contract_no = models.CharField(max_length=100, blank=True)
partner_name = models.CharField(max_length=200, blank=True)
value = models.DecimalField(max_digits=11, decimal_places=2,
blank=True, null=True)
platform = models.CharField(max_length=100, blank=True,
choices=PLATFORM)
views.py
def json_example(request):
return render(request, 'app/json_example.html')
def chart_data(request):
dataset=Contract.objects.all().values('platform').
exclude(platform='').annotate(Sum('value')).order_by('value__sum')
platform_name = dict()
for platform_tuple in Contract.PLATFORM:
platform_name[platform_tuple[0]] = platform_tuple[1]
chart = {
'chart': {'type': 'pie'},
'title': {'text': 'Contract Value for Every platform'},
'series': [{
'name': 'Platform',
'data': list(map(lambda row: {'name':
platform_name[row['platform']],
'y': row['value__sum']}, dataset))
}]
}
return JsonResponse(chart)
urls.py
url('json_example/', views.json_example, name='json_example'),
url('json_example/data/', views.chart_data, name='chart_data'),
json_example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contract Inventory Highcharts Example</title>
</head>
<body>
<div id="container" data-url="{% url 'chart_data' %}"></div>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
Highcharts.chart("container", data);
}
});
</script>
</body>
</html>
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
Your json data doesn't contain chart options. It should be something like this:
'{"title":{"text":"Title"},"series":[{"name":"Installation","data":[43934,52503,57177,69658,97031,119931,137133,154175]}]}'
What's more, you should parse json to js object before passing it to Highcharts constructor:
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var chartData = JSON.parse(data);
Highcharts.chart("container", chartData);
}
});
</script>
Check the example:
https://jsfiddle.net/BlackLabel/7zfyhnbr/
You have to format the data in such a way that it should match the highcharts ploting object. Please checkout the below code.
data = [
{"platform": "IPTV", "value__sum": "0.00"},
{"platform": "METRO E", "value__sum": "71372564.20"},
{"platform": "EDGE", "value__sum": "73867073.63"},
{"platform": "SYSTEM", "value__sum": "135465418.85"},
{"platform": "IPCORE", "value__sum": "467810178.41"}];
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
You have to update your code like below
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var data = JSON.parse(data);
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
}
});
</script>
I've manage to solve it by updated my views.py using django rest API and my template accordingly. Here is my updated code:
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'app/charts.html')
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
totalvendor= Contract.objects.all().values("vendor_name_id__name").
annotate(Count("id")).order_by('-id__count')[:8]
labels = totalvendor.values_list('vendor_name_id__name')
default_items = totalvendor.values_list('id__count', flat=True)
default_items = list(default_items)
data = {
"labels": labels,
"default": default_items,
}
return Response(data)
Pass an array from queryset to template and js
Here is my urls.py
url(r'^chart/', views.ChartView.as_view(), name='chart'),
url(r'^api/chart/data/$', ChartData.as_view(), name='chartdata'),
Here my code for charts.html
<script>
{% block jquery %}
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.default
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart");
var ctx2 = document.getElementById("myChart2");
var myChart = new Chart(ctx2, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Value Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title:{
display:true,
text:'Count Contract for Every Platform',
fontSize:18,
position:'top'
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000'
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var myChart = new Chart(ctx, {
type: 'polarArea',
data: {
labels: labels,
datasets: [{
label: 'Count Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
// var ctx = document.getElementById("myChart");
{% endblock %}
</script>
{% block content %}
<div class='row'>
<div class='col-sm-12' url-endpoint='{% url "chartdata" %}'>
<h1>Data Presentation</h1>
<div class=''>
<div class='col-sm-6'>
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<div class='col-sm-6'>
<canvas id="myChart2" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
{% endblock content %}
Anyway thanks to those who answered my questions
I would like to use json in chartJS. In first example I used
["0","76","32","88"]
and everything looks great.
Problem is in second example when I want to use JSON data as:
var json =[{"wartosc":"0"},{"wartosc":"76"},{"wartosc":"32"},{"wartosc":"88"}];
In variable chartjsData i want to have data as ["0","76","32","88"] but it doesn't work.
var json =[{"wartosc":"0"},{"wartosc":"76"},{"wartosc":"32"},{"wartosc":"88"}];
var chartjsData = [];
for (var i = 0; i < json.lenght; i++) {
chartjsData.push (json[i].wartosc);
}
var areaChartData = {
labels: ["j","j","j","j"],
datasets: [
{
label: "Electronics",
fillColor: "rgba(210, 214, 222, 1)",
strokeColor: "rgba(210, 214, 222, 1)",
pointColor: "rgba(210, 214, 222, 1)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: ["0","76","32","88"]
},
{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: chartjsData
}
]
};
You misspelled .length
for (var i = 0; i < json.length; i++) {
chartjsData.push (json[i].wartosc);
}
i am trying to use chart js to create a dashboard. i am trying to being with a the example given their getting started page. but color of the bars are always gray. i know i am missing something very trivial but i cannot figure out what. any help will be hugely appreciated
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/Chart.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//var ctx = $("#myChart");
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
</script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
</body>
</html>
Just add backgroundColor to your dataset to change the color of all bars.
...
backgroundColor: 'rgba(121, 121, 255, 0.2)',
...
If you pass it an array of colors, it will set the color bar by bar for the dataset
...
backgroundColor: ['rgba(121, 121, 255, 0.2)', 'rgba(255, 121, 121, 0.2)',... ],
...
Fiddle - http://jsfiddle.net/L9qsb3h4/
Fiddle (bar by bar) - http://jsfiddle.net/0b98k2g8/
I am trying to set the content of an info window but I am having syntax errors accessing the JSON object.
Example from elsewhere on Stack Overflow I am following
JavaScript snippet:
var localLayer = new google.maps.Data();
localLayer.loadGeoJson('JSON/local.geojson');
localLayer.setMap(map);
var localInfoWindow = new google.maps.InfoWindow({
var address = localLayer.features.properties.Address;
content: "<h3>" + address + "</h3>"
});
google.maps.event.addListener(localLayer, 'click', function(event){
localInfoWindow.setPosition(event.feature.getGeometry().get());
localInfoWindow.open(map, localLayer);
});
What am I doing wrong?
JSON snippet:
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "OBJECTID": 1, "Address": "14300 McMullen Highway SW", "City": "Cumberland", "State": "MD", "Zip_Code": 21502, "Type": "Detention Center", "Agency_Nam": "Allegany County Detention Center", "County": "Allegany" }, "geometry": { "type": "Point", "coordinates": [ -78.823195987258302, 39.598971947812366 ] } },
{ "type": "Feature", "properties": { "OBJECTID": 2, "Address": "131 Jennifer Road", "City": "Annapolis", "State": "MD", "Zip_Code": 21401, "Type": "Detention Center", "Agency_Nam": "Anne Arundel County Detention Center", "County": "Anne Arundel" }, "geometry": { "type": "Point", "coordinates": [ -76.530041483218611, 38.988903980495373 ] } }, . . .
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Maryland Prisoner Map</title>
<!--jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!--Google Maps API-->
<script src="http://maps.googleapis.com/maps/api/js"></script>
<!--Stamen Basemaps-->
<script type="text/javascript" src="http://maps.stamen.com/js/tile.stamen.js?v1.3.0"></script>
<!--CSS-->
<link href="style.css" rel="stylesheet" type="text/css">
<!--JavaScript-->
<script src="script.js" type="text/javascript"></script>
</head>
<body class="page-wrap">
<h1 id="header">Maryland Prisoner Map</h1>
<p></p>
<div id="map"></div>
</body>
</html>
CSS:
#header {
text-align: center;
}
#map {
height: 450px;
width: 80%;
margin: 0 auto;
border: 1px solid black;
box-shadow: 2px 2px 1px 2px gray;
}
* {
margin: 0;
}
html, body {
height: 100%;
}
JavaScript:
$(document).ready(function() {
var layer = "toner-lite";
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(39.290385, -76.612189),
zoom: 10,
mapTypeId: layer,
mapTypeControlOptions: {
mapTypeIds: [layer, google.maps.MapTypeId.HYBRID]
}
});
map.mapTypes.set(layer, new google.maps.StamenMapType(layer));
//load data into map
var localLayer = new google.maps.Data();
localLayer.loadGeoJson('JSON/local.geojson');
localLayer.setMap(map);
var localInfoWindow = new google.maps.InfoWindow({
var address = localLayer.features.properties.Address;
content: "<h3>" + address + "</h3>"
});
google.maps.event.addListener(localLayer, 'click', function(event){
localInfoWindow.setPosition(event.feature.getGeometry().get());
localInfoWindow.open(map, localLayer);
});
var stateLayer = new google.maps.Data();
stateLayer.loadGeoJson('JSON/state.geojson');
stateLayer.setMap(map);
var stateInfoWindow = new google.maps.InfoWindow({
content: "I am a state level jail or prison"
});
google.maps.event.addListener(stateLayer, 'click', function(event){
stateInfoWindow.setPosition(event.feature.getGeometry().get());
stateInfoWindow.open(map, stateLayer);
});
var federalLayer = new google.maps.Data();
federalLayer.loadGeoJson('JSON/federal.geojson');
federalLayer.setMap(map);
var federalInfoWindow = new google.maps.InfoWindow({
content: "I am a federal level jail or prison"
});
google.maps.event.addListener(federalLayer, 'click', function(event){
federalInfoWindow.setPosition(event.feature.getGeometry().get());
federalInfoWindow.open(map, federalLayer);
});
var marylandLayer = new google.maps.Data();
marylandLayer.loadGeoJson('JSON/maryland.geojson');
//give the map style
marylandLayer.setStyle(function(feature) {
return {
fillColor: getColor(feature.getProperty('Difference')), // call function to get color for state based on the COLI (Cost of Living Index)
fillOpacity: 0.9,
strokeColor: '#FFFFFF',
strokeWeight: 1,
zIndex: 1
};
});
//set layer to map
marylandLayer.setMap(map)
//get some color
function getColor(Difference) {
return Difference >= 94 ? '#b10026' :
Difference > 76 ? '#e31a1c' :
Difference > 58 ? '#fc4e2a' :
Difference > 38 ? '#fd8d3c' :
Difference > 20 ? '#feb24c' :
Difference > 7 ? '#fed976' :
Difference > 1 ? '#ffffb2' :
Difference > -1 ? '#FFFFFF' :
'#000000';
};
// Add mouseover and mouse out styling for the GeoJSON Maryland data
marylandLayer.addListener('mouseover', function(e) {
marylandLayer.overrideStyle(e.feature, {
strokeColor: '#2a2a2a',
strokeWeight: 2,
zIndex: 2
});
});
marylandLayer.addListener('mouseout', function(e) {
marylandLayer.revertStyle();
});
var polygonInfoWindow = new google.maps.InfoWindow({
content: marylandLayer.features.properties.Difference
});
google.maps.event.addListener(marylandLayer, 'click', function(event){
polygonInfoWindow.setPosition(event.feature.getGeometry().get());
polygonInfoWindow.open(map, marylandLayer);
});
});
You need to load the content into the infowindow inside the layer 'click' listener. Inside that function evt is a reference to the feature and you can call the getProperty method to access that feature's properties:
localLayer.addListener('click', function (evt) {
var address = evt.feature.getProperty("Address");
localInfoWindow.setContent("<h3>" + address + "</h3>");
localInfoWindow.setPosition(evt.feature.getGeometry().get());
localInfoWindow.open(map);
});
proof of concept fiddle