pyecharts自适应屏幕居中显示
pyecharts自适应屏幕居中显示
pyecharts生成的html默认是靠左上显示的,使用的pyecharts版本是1.9.0。
期望图像是居中显示!
画图代码如下
c = (
Graph()
.add("Measure", nodes, links, categories, repulsion=4000, gravity=0.1)
.set_global_opts(title_opts=opts.TitleOpts(title="Graph-Measures"))
.render("graph_base.html")
)
解决方法
通过修改配置文件来解决上述问题,分以下几步:
- 找到pyecharts的安装位置:
Windows环境下
where python
我这里使用的虚拟环境
C:\Users\XXXX\.conda\envs\USTC
所以待修改的配置文件路径为
C:\Users\XXXX\.conda\envs\USTC\Lib\site-packages\pyecharts\render\templates
- 修改文件 macro,
macro文件修改后的前半部分为:
{%- macro render_chart_content(c) -%}
// **修改**居中和百分比显示区域
<div id="{{ c.chart_id }}" class="chart-container" style="width:95%; height:95%; margin:auto; top:30px"></div>
<script>
var chart_{{ c.chart_id }} = echarts.init(
document.getElementById('{{ c.chart_id }}'), '{{ c.theme }}', {renderer: '{{ c.renderer }}'});
{% for js in c.js_functions.items %}
{{ js }}
{% endfor %}
var option_{{ c.chart_id }} = {{ c.json_contents }};
chart_{{ c.chart_id }}.setOption(option_{{ c.chart_id }});
{% if c._is_geo_chart %}
var bmap = chart_{{ c.chart_id }}.getModel().getComponent('bmap').getBMap();
{% if c.bmap_js_functions %}
{% for fn in c.bmap_js_functions.items %}
{{ fn }}
{% endfor %}
{% endif %}
{% endif %}
{% if c.width.endswith('%') %}
window.addEventListener('resize', function(){
chart_{{ c.chart_id }}.resize();
})
{% endif %}
</script>
// 添加自适应刷新函数
<script>
//窗口大小变化时候,进行刷新页面操作,防止样式混乱
var x=window.innerWidth;
function resizeFresh(){
if(x!=window.innerWidth)
location.reload();
}
</script>
{%- endmacro %}
- 修改simple_chart.html
修改后如下所示:
{% import 'macro' as macro %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ chart.page_title }}</title>
{{ macro.render_chart_dependencies(chart) }}
</head>
<body onresize="resizeFresh()"> <!-- 添加刷新函数调用 -->
<!-- 添加刷新函数调用-->
<style type="text/css">
html,body{
height:100%;
width:100%
}
</style>
{{ macro.render_chart_content(chart) }}
</body>
</html>
重新运行代码即可!