pyecharts 自适应屏幕居中显示
pyecharts生成的html默认是靠左上显示的
需要生成的文件居中显示,且能根据浏览器窗口大小自动调整需要修改html
当然,如果你是熟悉html,且只是临时少量生成表格的话,每次生成完后手动修改html文件的几个数据即可
需要修改参数:
- 1.获取浏览器窗口长和宽
- 2.设置显示区域长宽百分比:width:95%; height:95%;
- 3.设置居中参数:margin:auto;
- 4.设置自适应(刷新页面):location.reload();
如果你想自动生成的话,可以了解一下以下内容
修改pyecharts render配置文件
文件路径(python安装目录): xxx\Lib\site-packages\pyecharts\render\templates
- 1. 修改文件 macro文件
修改居中和百分比显示区域
<div id="{{ c.chart_id }}" class="chart-container" style="width:95%; height:95%; margin:auto; top:30px"></div>
添加自适应刷新函数
<script>
//窗口大小变化时候,进行刷新页面操作,防止样式混乱
var x=window.innerWidth;
function resizeFresh(){
if(x!=window.innerWidth)
location.reload();
}
</script>
修改后开始部分
{%- 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 %}
</script>
<script>
//窗口大小变化时候,进行刷新页面操作,防止样式混乱
var x=window.innerWidth;
function resizeFresh(){
if(x!=window.innerWidth)
location.reload();
}
</script>
{%- endmacro %}
- 2. 修改simple_chart.html
获取宽度、高度
<style type="text/css">
html,body{
height:100%;
width:100%
}
</style>
添加刷新函数调用
<body onresize="resizeFresh()">
修改后文件如下
{% import 'macro' as macro %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{ chart.page_title }}</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=yes">
{{ macro.render_chart_dependencies(chart) }}
<style type="text/css">
html,body{
height:100%;
width:100%
}
</style>
</head>
<body onresize="resizeFresh()">
{{ macro.render_chart_content(chart) }}
</body>
</html>
大概看下效果,缩小网页窗口显示区会随比例缩小
具体代码修改参考资源文件
注: pyecharts版本1.7.1,后期版本可能会优化该问题