I am trying to use images as legend in Google Charts. This is how it currently looks like:
And this is how it should look like:
This is my JavaScript code to draw the chart:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Champions', 'Games', 'Wins', 'Loses'],
['Ezreal', 21830, 12172, 9658],
['Taric', 17835, 9658, 8177],
['Graves', 13567, 6558, 7009],
['Lee Sin', 12738, 6349, 6389],
['Blitzcrank', 11965, 6132, 5833],
['Nunu', 10946, 5407, 5539],
['Sona', 9660, 5226, 4434],
['Corki', 9457, 4389, 5068],
['Jax', 8669, 4358, 4311],
['Amumu', 8396, 4743, 3653]
]);
var options = {
title: 'Most played',
backgroundColor: '#EEEEEE',
hAxis: {title: 'Champions', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('most-popular'));
chart.draw(data, options);
}
I already tried to embed the <img> tags into the array like this:
['<img src="img/ezreal.png">'Ezreal', 21830, 12172, 9658]
Unfortunately, Google Charts does some kind of escape that string so that the whole HTML code is shown.
So I am looking for a way to include those images with Google Charts. If that is not possible I am looking for other JavaScript libraries which could do the job.
it is not possible! ( short answer, on mobile)
Related
I would like to set the colors in a google chart from my code, and not sure how to do it. I have this in a cshtml page.
<script type="text/javascript">
// Load the Visualization API and the piechart package.
//google.load('visualization', '1.0', { 'packages': ['bar'] });
google.load('visualization', '1.0', { 'packages': ['corechart'] });
var visualization;
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);
function drawCharts() {
var titleName = "Rounding Eligible";
$("#chartHeader").html(titleName);
var options = {
'backgroundColor': 'transparent',
title: titleName,
subtitle: 'Range of ddd to ddd', seriesType: "bars",isStacked: true,
series: { 0:{color:"#009add"} ,1:{color:"#009844"} ,2: {color:"#ef7521"} ,3: {color:"#89d2e6"},4:{color:"#82bc00"},5:{color:"#f19f53"},6:{color:"#0055b7"},#(Model.NumSeries) : { type: "line", visibleInLegend: false, color: "#FF0000" }},
vAxis:{title: "Count", minValue:10}
};
// Create the data table.
var data = google.visualization.arrayToDataTable(#Html.Raw(Model.ChartJson));
var chart_div = document.getElementById('chartDiv');
var chart = new google.visualization.ComboChart(chart_div);
chart.draw(data, options);
//setup a temp image to gold hold the chart
createHiddenImage('hiddenCanvas1', 'chartDiv', chart.getImageURI());
}
</script>
What I would like to do is replace my colors ( 0:{color:"#009add"} ,1:{color:"#009844"}) to be based on something in the code and do something like
isStacked: true,
series:
#foreach seriesvalue in #Model.seriesValues
{#Html.Raw(seriesvalue);},
Axis:{title: "Count", minValue:10}
I have no idea what is possible to accomplish this, is it best to just pass the whole options object from the model? Basically I can't figure out how to do it.
Just use JSON serialization:
series: #Html.Raw(JsonConvert.SerializeObject(Model.seriesValues))
You'll want to make seriesValues a Dictionary keyed by the number you want associated with each color.
For a deeper dive, see this answer: Using Razor within JavaScript
You can access properties from your model anywhere on the page, including within the script, via:
#Model.MyPropertyName
With that in mind, your javascript can look something like this:
myColor = '#Model.MyGreenColorProperty';
Note the single quotations around the #Model... this is very important, and will not work if the value is not surrounded by the quotes.
I'm trying to create a Bar Chart using Google's jsapi, and I've downloaded the following code (with my own changes), that needs to create Bar Chart.
google.load("visualization", "1", {packages:["corechart"]});
drawChart(AvgTimeInConference, keysSorted3);
function drawChart(AvgTimeInConference, keysSorted3) {
var DataTable=[];
DataTable.push(['Conference', 'Average Duration']);
for (var i=0; i<keysSorted3.length; i++)
{
if(keysSorted3[i]!=="")
{
var x=[keysSorted3[i], AvgTimeInConference[keysSorted3[i]]];
DataTable.push(x);
}
}
var data = new google.visualization.arrayToDataTable(DataTable);
var options = {
title: 'average durations length of the conferences, grouped by Conference Type',
vAxis: {title: 'Average Duration', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
The code works greate, until it gets to the line "var data = new google.visualization.arrayToDataTable(DataTable);". Data Table at this point is an array that contains the data in cells (first cell - headers, second and on are the data according to headers). When trying to use that function, the run get stuck and doesn't move on. doe's anyone has an idea why it happens? is DataTable not in the right format? Thanks!
Edit: The DataTable object from debug
i am using google chart to render charts, but sometimes the label is too long that the chart gets chopped, sometimes the chart is so long that the label gets cutting off, please check jsfiddle to see.
google.load('visualization', '1', {packages: ['corechart']});
var graphTitle = '', dataPoints = [];
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Option', 'Percent'],
['More than 75%', 47],
['50% to 74%', 36],
['30% to 49%', 10],
['10% to 29%', 4],
['Less than 10%', 3]
]);
$('body').data('quickpoll_179', data);
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('quickpollChart')).
draw(data, {
title:'',
titleTextStyle: {color: '#000000'},
width:640, height:340,
legend: {position:'none'},
vAxis: {title: ""},
hAxis: {title: "",format:"#'%'"},
colors: ['#74317D'],
chartArea: {left:80.6,top:20, width:539.4,height:"340px"}
});
}
google.setOnLoadCallback(drawVisualization);
my question is how can i calc the proper width so if the chart is large, i can increase the whole container size and stop chart and lable being cutting off. i know for this case, i can increase the chart area, but it may not be applicable in every curcumstances. so it is better that i know how much space the google chart will take so i can dymaically resize the width and height of the container
I would say just decrease the size of the font, This is the default behaviour for a Google chart you cannot work with everything, what if the label was 1000 characters long. Then you would want the ellipse, you can still hover over the label to see the full text.
See updated fiddle: http://jsfiddle.net/9J4sS/1/
I achieved this by lowering the size of the text.
vAxis: {
title: "",
textStyle: {
fontSize:8
}
}
Or alternatively display your labels inside your graph using. http://jsfiddle.net/9J4sS/2/
vAxis: {
title: "",
textPosition: "in"
}
I'm creating a handful of pie charts using Google Charts. The majority of the graph options for the charts I'm creating are the same, except the titles. Is it possible to maintain a default set of options but write certain specific options for each graph (in this case, I just need to set a title).
Here's an example of the code I'm using:
var graphOptions = {
is3D: true,
pieSliceText: 'label',
colors: ['#F9B641', '#FBCB75', '#FCE1B0', '#FFF8EB', '#FFFFFF'],
backgroundColor: 'transparent',
titleTextStyle: {
color: '#FFF'
},
legend: {
textStyle: {
color: '#FFF'
}
},
chartArea: {
width: '90%',
height: '80%'
}
};
function pieChart1() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 216],
['Female', 238]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart1'));
chart.draw(data, graphOptions);
}
function pieChart2() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 116],
['Female', 98]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart2'));
chart.draw(data, graphOptions);
}
How would I go about setting the title option for each graph while still pulling the options from graphOptions?
As David explained, you can create an options object, and then edit properties of that object individually.
Here is a jsfiddle that shows it in action.
Note: you cannot see the titles because the BG and font color is white. Just do a ctrl+a to select everything and see them hidden there
Basically, you create a variable both functions can access (in your case graphOptions). In each function you set a new variable called options to equal graphOptions. You can then change the title property of the options variable to whatever you want without changing your default options template graphOptions, and use the options variable to draw the graph.
For your code, that means adding this code to each function:
var options = graphOptions;
options.title = "Pie Chart X"
You can change the title to whatever is appropriate, different for each graph. Then in the graph draw command, you change graphOptions to options to get
chart.draw(data, options);
Normally you'd do:
var options = { title: 'My Chat Title' };
In your case add title to your graphOptions object then do:
graphOptions.title = "The New Title";
for each graph.
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
var myData = {
'Mushrooms': 3,
'Onions': 1,
'Olives': 1,
'Zucchini': 1,
'Pepperoni': 2
};
var rows = [];
for (element in myData) {
rows.push([element + " (" + myData[element] + ")", myData[element]])
}
data.addRows(rows);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':450,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Example fiddle
How do I remove padding or margins in this example?
By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:
// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
'width': 350,
'height': 400,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'bottom'}
};
If you want to tune it more, try changing these values or using other properties from the link above.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.
For anyone interested, here is the actual solution:
... //rest of options
width: '100%',
height: '350',
chartArea:{
left:5,
top: 20,
width: '100%',
height: '350',
}
... //rest of options
The key here has nothing to do with the "left" or "top" values. But rather that the:
Dimensions of both the chart and chart-area are SET and set to the SAME VALUE
As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.
It's missing in the docs (I'm using version 43), but you can actually use the right and bottom property of the chart area:
var options = {
chartArea:{
left:10,
right:10, // !!! works !!!
bottom:20, // !!! works !!!
top:20,
width:"100%",
height:"100%"
}
};
So it's possible to use full responsive width & height and prevent any axis labels or legends from being cropped.
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
There is this possibility like Aman Virk mentioned:
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
But keep in mind that the padding and margin aren't there to bother you.
If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.
If you take away that margin then you will end up showing only a part of the labels or no labels at all.
So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.