Make highcharts fullscreen also fullscreen the div wrapping the chart - javascript

Is there a way to make the div wrapping the chart part of the fullscreen as well?
This is my code: fiddle
THis code only fulscreens the chart. When I try and do to point the div I need in the fullscreen:
Highcharts.FullScreen = function(container) {
this.init(ontainer.parentNode.parentNode);
};
My fullscreen is getting cut off and also not adding the parent div to the full screen. Is there to make the whole div with id yo and the other div inside (<div>Random Data and text.......</div>) as part of the fullscreen?

You can connect the content of a custom element through chart.renderer.text().add() by specifying this element with the html() method:
chart.renderer.text(selector.html(), 0, 0).add();
...hiding this element through css, set the display: none:
.random_data {
display: none;
}
This is the piece of code to add:
function (chart) {
chart.renderer
.text($(".random_data").html(), 10, 10)
.css({
color: "green",
fontSize: "12px",
})
.add();
}
JavaScript:
let chart = Highcharts.chart(
"container",
{
chart: {
type: "column",
},
title: {
text: "",
},
xAxis: {
categories: ["one", "two", "three"],
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0,
},
},
yAxis: {
title: {
text: "",
},
endOnTick: false,
},
series: [
{
name: "books",
data: [
["one", 64161.71548379661],
["two", 3570.6197029028076],
["three", -200.70625619033547],
],
marker: {
symbol: "circle",
},
},
],
},
function (chart) {
chart.renderer
.text($(".random_data").html(), 10, 10)
.css({
color: "green",
fontSize: "12px",
})
.add();
}
);
let btn = document.getElementById("btn");
btn.addEventListener("click", function () {
Highcharts.FullScreen = function (container) {
console.log(container.parentNode.parentNode);
this.init(container.parentNode); // main div of the chart
};
Highcharts.FullScreen.prototype = {
init: function (container) {
if (container.requestFullscreen) {
container.requestFullscreen();
} else if (container.mozRequestFullScreen) {
container.mozRequestFullScreen();
} else if (container.webkitRequestFullscreen) {
container.webkitRequestFullscreen();
} else if (container.msRequestFullscreen) {
container.msRequestFullscreen();
}
},
};
chart.fullscreen = new Highcharts.FullScreen(chart.container);
});
CSS:
.random_data {
display: none;
}
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="yo">
<div class="random_data">Random Data and text.......</div>
<div id="container" style="height: 400px; margin-top: 1em;"></div>
</div>
<button id="btn">
Show full screen
</button>

Related

Adding Context to Django View Causing My Highcharts Map to Disappear

This is my first Django project, and I am working on a Django html template that should contain a Chart.JS bar graph (https://www.chartjs.org/docs/latest/charts/bar.html) alongside a Highcharts drilldown map of the US (https://www.highcharts.com/demo/maps/map-drilldown).
I've successfully implemented my Chart.JS bar graph and passed data to it from our AWS RDS. But now when I try to implement even just the stock Highcharts code from their website, the map fails to render at all. After trying to isolate the problem, I've found that the map does render if I simply delete "context" from the return statement in my view (i.e. delete "context" from the final line in my first block of code below). But this obviously then inhibits my bar graph from rendering. I think I must be missing something with how the highcharts data is loaded in the presence of other context data, but I've been unable to fix it such that both the graph and map render. Any help would be greatly appreciated!
My Django View:
def index(request):
mydb = mysql.connector.connect(
host=xxxx,
user=xxxx,
password=xxxx,
database=xxxx
)
mycursor = mydb.cursor()
mycursor.execute("WITH CS1 AS (SELECT cts.Name, cts.State, m.Frequently, m.Always FROM Masks m JOIN Counties cts ON (m.FIPS = cts.FIPS)) SELECT CS1.State, AVG((CS1.Frequently+CS1.Always)*100) AS Perc_High_Frequency FROM CS1 WHERE CS1.State<>'Puerto Rico' GROUP BY CS1.State ORDER BY Perc_High_Frequency DESC")
tempList = mycursor.fetchall()
statesMaskName = [item[0] for item in tempList]
statesMaskPerc = [item[1] for item in tempList]
context={'statesMaskName':statesMaskName, 'statesMaskPerc':statesMaskPerc}
return render(request,'index.html', context)
The relevant HTML/JS:
<html lang="en" dir="ltr">
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="fixed-header">
<h1>COVID-19 Sentiment and Mask Practices</h1>
</div>
<div>
<div class="col-lg-3" style="float: left; max-height: 6500px;max-width:400px;overflow: scroll; overflow-x:hidden;">
<div style="background-color: #17202A;">
<span style="color: #F7F9F9; text-align: center;"><h4>% Population Who "Frequently" or "Always" Wear Masks When In Public Within 6" of Others (as of July 2-14, 2020)</h4></span>
</div>
<div class="col-lg-12">
<form method="post" enctype="multipart/form-data" action="selectState">
{% csrf_token %}
<div class="col-lg-4" style="float: left; max-height: 3000px;">
<br><br style="line-height: 15px"/>
{% for state in statesMaskName %}
<table style="border-width: 2px; border: #333;">
<tr>
<input type="submit" value="{{state}}" name="statesMaskName" style="width:130px;">
</tr>
</table>
{% endfor%}
</div>
<div style="float: left;">
<canvas id="myChart" height="1360" width="250"></canvas>
</div>
</form>
</div>
</div>
<div class="col-lg-6">
</div>
<div class="col-lg-3">
</div>
</div>
<br>
</body>
<!--my updated code for chartjs graph-->
<script>
const labels = {{statesMaskName|safe}};
const data = {
labels: labels,
datasets: [{
label: '% Population',
color: 'orange',
backgroundColor: 'orange',
borderColor: 'orange',
data: {{statesMaskPerc|safe}},
}]
};
const config = {
type: 'bar',
data,
options: {
indexAxis: 'y',
color: 'white',
scales: {
y: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
},
display: false
},
x: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
// Include a % sign in the ticks
callback: function(value, index, values) {
return value + '%';
}
}
}
}
}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
<!--stock code for highcharts map-->
<div id="usMap" style="height: 500px; min-width: 310px; max-width: 800px; margin: 0 auto"></div>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/data.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="https://code.highcharts.com/maps/modules/offline-exporting.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<script type="text/javascript">
/*
TODO:
- Check data labels after drilling. Label rank? New positions?
*/
let data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']);
const separators = Highcharts.geojson(Highcharts.maps['countries/us/us-all'], 'mapline');
// Set drilldown pointers
data.forEach((d, i) => {
d.drilldown = d.properties['hc-key'];
d.value = i; // Non-random bogus data
});
function getScript(url, cb) {
const script = document.createElement('script');
script.src = url;
script.onload = cb;
document.head.appendChild(script);
}
// Instantiate the map
Highcharts.mapChart('usMap', {
chart: {
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
const chart = this,
mapKey = 'countries/us/' + e.point.drilldown + '-all';
// Handle error, the timeout is cleared on success
let fail = setTimeout(() => {
if (!Highcharts.maps[mapKey]) {
chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
fail = setTimeout(() => {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner
// Load the drilldown map
getScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', () => {
data = Highcharts.geojson(Highcharts.maps[mapKey]);
// Set a non-random bogus value
data.forEach((d, i) => {
d.value = i;
});
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
});
}
this.setTitle(null, { text: e.point.name });
},
drillup: function () {
this.setTitle(null, { text: '' });
}
}
},
title: {
text: 'Highcharts Map Drilldown'
},
subtitle: {
text: '',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series: [{
data: data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}, {
type: 'mapline',
data: separators,
color: 'silver',
enableMouseTracking: false,
animation: {
duration: 500
}
}],
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
</script>
</html>

Is it possible to use mouseenter and mouseleave event in chart js?

Right now I'm using onHover into each pie to add some scale/zoom, but I want to use mouseenter and mouseleave. So on mouseenter on each pie it will add some scale/zoom, and on mouseleave, I want it back to its original state.
either mouseenter-mouseleave or mouseover-mouseout is fine.
here is the codepen:
https://codepen.io/graydirt/pen/NWNZNyQ
Thanks guys!
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function (evt, elements) {
let segment;
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>
Your code is already designed to return to the original size on mouseout, but you have a subtle bug.
You need to define the segment variable outside the chart. With a saved reference to the segment, the mouseout event will fire and the onHover handler will return the pie to its original size.
Please see the attached example below:
let segment;
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function(evt, elements) {
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>

chart js when hover shows old values

When Dropdown selected change ıt shows previous selected values. I tried many ways like destroy the chart functionality but none of them work or I am not able to work it
any one can help me about the solution.
I have saw many answers about this question but none of them works ..
I have shared my code below so looking for help
let asyaIlceRuhsat = document.getElementById('asyaIlceRuhsat').getContext('2d');
$(document).ready(function () {
$('#mySelectAsya').select2({
width: '100%'
}).val() == -1 ? $('#asyaIlceRuhsat').after('<div class="asyaSecimi"><p class="text-center text-uppercase font-weight-bolder">Lütfen ilçe seçiniz!</p></div>') : null;
});
//Asya Yakası
$('#mySelectAsya').on('select2:select', function (e) {
var selectedId = $('#mySelectAsya').val()
var selectedText = $("#mySelectAsya :selected").text()
var canvas = document.getElementById('asyaIlceRuhsat')
if (selectedId === -1) {
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
$(".asyaSecimi").css("display", "block");
$(canvas).addClass("hidden");
}
else {
$(canvas).removeClass("hidden");
$(".asyaSecimi").css("display", "none");
}
fetch(`http://myurl/api/Web/Test/GetValue?query=${queryId}`)
.then(function (response) {
return response.json();
// console.log(response)
})
.then(function (ids) {
// console.info(`ids:`, ids)
new Chart(asyaIlceRuhsat, {
type: 'bar',
data: {
labels: ids.map(function (id) {
return id.TUR;
}),
datasets: [
{
label: "ARIZA",
backgroundColor: "#e65c00",
data: ids.map(function (id) {
return id.ARIZASAYISI;
}),
}, {
label: "ARIZA ONAY",
backgroundColor: "#66ff66",
data: ids.map(function (id) {
return id.ARIZAONAYSAYISI;
}),
}, {
label: "NORMAL",
backgroundColor: "#66ccff",
data: ids.map(function (id) {
return id.NORAMLSAYISI;
}),
}, {
label: "BAŞVURU",
backgroundColor: "#0099ff",
data: ids.map(function (id) {
return id.BASVURUSAYISI;
}),
},
]
},
options: {
title: {
display: true,
text: 'Normal Ruhsat Durum',
fontSize: 18
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#000',
usePointStyle: false
}
},
layout: {
padding: {
left: 0,
right: 0,
bottom: 0,
top: 0
}
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Asya Geneli Normal Ruhsat Durumları',
fontColor: '#000000',
fontSize: 12
}
}]
}
}
});
});
})
This is a very common issue while updating the same canvas with a new chart. On your dropdown change event try to add the following code which will destroy all the charts previous instance.
Chart.helpers.each(Chart.instances, function (instance) {
instance.destroy();
});

How to highlights bar when click echart bar graph?

I have created a bar graph using the echarts library. How can I highlight the bar graph when the user clicks on a bar, or else apply the bar border when a bar is clicked?
Is there a way to highlight a bar when the click event is triggered for the bar?
Yes, there is a way to highlight a bar when click.
When the click event is triggered, you can get the exactly data(single bar) be clicked from the parameter, then you only need to change color(For example, decrease alpha) of this data to achieve the 'highlight' goal.
And don't forget recovery color of other data(not clicked) at same time.
check this demo
let echartsObj = echarts.init(document.querySelector('#canvas'));
option = {
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
}],
yAxis: [{
type: 'value'
}],
series: [{
name: '直接访问',
type: 'bar',
barWidth: '60%',
data: [{
value: 10,
itemStyle: {
color: 'hsl(200,60%,45%)'
}
}, {
value: 52,
itemStyle: {
color: 'hsl(200,60%,45%)'
}
}, {
value: 200,
itemStyle: {
color: 'hsl(60,60%,45%)'
}
}, {
value: 334,
itemStyle: {
color: 'hsl(150,60%,45%)'
}
}, {
value: 390,
itemStyle: {
color: 'hsl(220,60%,45%)'
}
}, {
value: 330,
itemStyle: {
color: 'hsl(200,60%,45%)'
}
}, {
value: 220,
itemStyle: {
color: 'hsl(150,60%,45%)'
}
}]
}]
};
echartsObj.setOption(option)
echartsObj.on('click', function(params) {
console.log(params)
option.series[0].data.forEach((data, index) => {
if (index === params.dataIndex) {
if (!data.isChecked) {
data.itemStyle.color = getHighLightColor(data.itemStyle.color);
data.isChecked = true;
}
} else {
if (data.isChecked) {
data.itemStyle.color = getOrigColor(data.itemStyle.color);
data.isChecked = false;
}
}
})
echartsObj.setOption(option)
});
function getHighLightColor(color) {
return color.replace(/(\d+)%\)/, (...args) => {
return 20 + Number(args[1]) + '%)'
});
}
function getOrigColor(highlightColor) {
return highlightColor.replace(/(\d+)%\)/, (...args) => {
return Number(args[1]) - 20 + '%)'
});
}
<html>
<header>
<script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
</header>
<body>
<div id="canvas" style="width: 100%; height: 200px">
</div>
</body>
</html>
Can be highlight like this:
chart.on('click', (params) => {
chart.dispatchAction({
type: 'highlight',
seriesIndex: params.seriesIndex,
dataIndex: params.dataIndex
})
})
The highlight style can be set using emphasis.itemStyle
The document can be found here: https://echarts.apache.org/en/api.html#action.highlight

When echarts is switched on tab, the container width is set to 100%, but no matter how it is set, the width is only 100px

html
js
var myChart = echarts.init(document.getElementById("main"));
window.onresize = myChart.resize;
var statistics = {
title: {
text: "面积",
textStyle: {
fontWeight: "normal",
color: "#fff",
fontSize: 14
},
left: "center"
},
tooltip: {
// 鼠标移动柱状图是提示文字
show: true
},
legend: {
// data: ['面积'],
textStyle: {
fontSize: 12
}
},
xAxis: {
data: ["灌木", "森林", "森林", "树木", "小树", "大树", "红树"],
axisLabel: {
show: true,
textStyle: {
color: "#fff"
}
},
axisLine: {
lineStyle: {
color: "#094060"
}
}
},
yAxis: {
axisLine: {
lineStyle: {
color: "#094060"
}
},
axisLabel: {
show: true,
textStyle: {
color: "#fff"
}
},
splitLine: {
lineStyle: {
color: ["#07405c"]
}
}
},
itemStyle: {
color: "#06ae7c",
emphasis: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)"
}
},
series: [
{
type: "bar",
barWidth: 48,
data: [38, 23, 35, 12, 26, 8, 36]
}
]
};
myChart.setOption(statistics);
The echarts container in the tab switch width is set to 100%, but no matter how to set the width, are only 100px, the Internet that is because the tab bar tried to hide cause, many of the above methods, are not normal display, followed by window.onresize = myChart.resize in the code; only when changing the size of the browser window to display properly, but if you do not change the size of the window or after 100px, before we have encountered this kind of situation is how to solve?
put the class "echart" in each div chart, and execute that in your js.
$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
$(".echart").each(function() {
var id = $(this).attr('echarts_instance');
window.echarts.getInstanceById(id).resize();
});
});
I have discovered one workaround for this issue. Try to call the resize event of window object when you switch tabs. To achieve it with jQuery is straightforward:
$(window).trigger('resize');
var myChart=$("#myChart");
myChart.style.width=window.innerWidth+'px';
chartObj=echarts.init(myChart);
chartObj.setOption(option);

Categories