pyqt5使用echarts做數(shù)據(jù)可視化,可用pyinstaller打包

Echarts簡介

ECharts,縮寫來自 Enterprise Charts,商業(yè)級數(shù)據(jù)圖表,是百度的一個開源的數(shù)據(jù)可視化工具。目前,非常美觀,非常好用,非常受歡迎的數(shù)據(jù)可視化工具。
官方網(wǎng)址:https://echarts.apache.org/zh/index.html

后來,有大神開發(fā)了Pyecharts, 是一個用于生成 Echarts 圖表的python類庫,也非常好用。

關(guān)于ECharts和Pyecharts的資料網(wǎng)上非常多,就不細述了,大家自己找吧。

本文主要講Pyqt5和Pyecharts的結(jié)合使用,Pyqt5和ECharts的結(jié)合使用。

Pyqt5的數(shù)據(jù)可視化

在講ECharts和Pyecharts之前,先說下pyqt5的數(shù)據(jù)可視化。

pyqt5的數(shù)據(jù)可視化工具很多。有pyqt5自帶的QtChart可以做,有PyQtGraph可以做,有Plotly可以做,當然還有Pyecharts和Echarts可以做,等等等等。

個人也剛開始做數(shù)據(jù)可視化,這幾個工具都摸了一下,發(fā)現(xiàn)最后還是Pyecharts和Echarts最好用,最美觀,最方便。

而且,考慮到pyqt5打包的問題,這幾個庫(除了QtChart),都存在同樣的困難。所以,最終我選的就是Pyecharts和Echarts。

Pyecharts和Echarts,為什么我一直分開說呢?因為在pyqt5的程序里,你可以單單使用Pyecharts來實現(xiàn)數(shù)據(jù)可視化,也可以單單使用Echarts來實現(xiàn)數(shù)據(jù)可視化。

Pyecharts和Echarts的底層原理肯定是一樣的,但在pyqt5的程序里去實現(xiàn),差別卻很大。

Pyecharts相對方便,因為直接用的python語言來實現(xiàn),但有個問題讓我無法接受,因為用pyinstaller竟然無法打包Pyecharts! 網(wǎng)上關(guān)于這個問題的解決方案很多,但我嘗試了,都沒有用。我還嘗試去修改Pyecharts源碼,大半天也沒實現(xiàn),終于放棄。

最后,通過一位大神的文章《Python數(shù)據(jù)可視化:PyQt與ECharts的完美結(jié)合方案》,發(fā)現(xiàn)在pyqt5的程序里,直接使用echarts,其實也很方便,很好用,而且使用pyinstaller打包,無任何障礙,因為根本沒有不需要加載任何類庫模塊,就是直接編輯HTML文本就行了。

下面,Pyecharts和Echarts的兩種實現(xiàn)代碼,我都分享一下,希望對大家有幫助。

廢話不說,上代碼。

pyqt5和pyecharts的結(jié)合使用,但無法使用pyinstaller打包

【如下代碼,完全復制,直接運行,即可使用】

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import QWebEngineView

from pyecharts.charts import Line
from pyecharts import options
################################################
#######創(chuàng)建主窗口
################################################
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('My Browser')
        self.showMaximized()

        self.webview = QWebEngineView()
        self.setCentralWidget(self.webview)
        ###############################################
        self.goto_creat_pyecharts()



    def goto_creat_pyecharts(self):
        ######################################################
        the_abscissa_list = ["周一","周二","周三","周四","周五","周六","周日"]
        the_allmoney_list = [800,700,500,600,500,400,900]
        the_allpoints_list = [200,300,100,200,300,100,400]
        ######################################################
        line = (
            Line()
                .add_xaxis(xaxis_data=the_abscissa_list)
                .add_yaxis(series_name="營業(yè)總額", y_axis=the_allmoney_list, symbol="circle", is_symbol_show=True,is_smooth=True,is_selected=True)
                .add_yaxis(series_name="積分總額", y_axis=the_allpoints_list, symbol="circle", is_symbol_show=True,is_smooth=True,is_selected=True)
                .set_global_opts(title_opts=options.TitleOpts(title="每周營收折線圖"))
        )

        #############################################
        the_sourceFile_origin = ("D:/monthcountview.html")
        line.render(path=the_sourceFile_origin)
        self.webview.load(QUrl.fromLocalFile(the_sourceFile_origin))



################################################
#######程序入門
################################################
if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


pyqt5和echarts的結(jié)合使用,可以使用pyinstaller打包

【如下代碼,完全復制,直接運行,即可使用】

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtWebEngineWidgets import QWebEngineView


################################################
#######創(chuàng)建主窗口
################################################
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setWindowTitle('My Browser')
        self.showMaximized()

        self.webview = QWebEngineView()
        self.setCentralWidget(self.webview)
        ###############################################
        self.goto_creat_echarts_html()






    def goto_creat_echarts_html(self):
        ###################################################
        the_html_content ='''
        <!--
    THIS EXAMPLE WAS DOWNLOADED FROM https://echarts.apache.org/examples/zh/editor.html?c=dataset-link
-->
<!DOCTYPE html>
<html style="height: 100%">
    <head>
        <meta charset="utf-8">
    </head>
    <body style="height: 100%; margin: 0">
        <div id="container" style="height: 100%"></div>

        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
        <!-- Uncomment this line if you want to dataTool extension
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/dist/extension/dataTool.min.js"></script>
        -->
        <!-- Uncomment this line if you want to use gl extension
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-gl@2/dist/echarts-gl.min.js"></script>
        -->
        <!-- Uncomment this line if you want to echarts-stat extension
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-stat@latest/dist/ecStat.min.js"></script>
        -->
        <!-- Uncomment this line if you want to use map
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/map/js/china.js"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/map/js/world.js"></script>
        -->
        <!-- Uncomment these two lines if you want to use bmap extension
        <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=<Your Key Here>"></script>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/dist/extension/bmap.min.js"></script>
        -->

        <script type="text/javascript">
var dom = document.getElementById("container");
var myChart = echarts.init(dom);
var app = {};

var option;



setTimeout(function () {

    option = {
        legend: {},
        tooltip: {
            trigger: 'axis',
            showContent: false
        },
        dataset: {
            source: [
                ['product', '2012', '2013', '2014', '2015', '2016', '2017'],
                ['Milk Tea', 56.5, 82.1, 88.7, 70.1, 53.4, 85.1],
                ['Matcha Latte', 51.1, 51.4, 55.1, 53.3, 73.8, 68.7],
                ['Cheese Cocoa', 40.1, 62.2, 69.5, 36.4, 45.2, 32.5],
                ['Walnut Brownie', 25.2, 37.1, 41.2, 18, 33.9, 49.1]
            ]
        },
        xAxis: {type: 'category'},
        yAxis: {gridIndex: 0},
        grid: {top: '55%'},
        series: [
            {type: 'line', smooth: true, seriesLayoutBy: 'row', emphasis: {focus: 'series'}},
            {type: 'line', smooth: true, seriesLayoutBy: 'row', emphasis: {focus: 'series'}},
            {type: 'line', smooth: true, seriesLayoutBy: 'row', emphasis: {focus: 'series'}},
            {type: 'line', smooth: true, seriesLayoutBy: 'row', emphasis: {focus: 'series'}},
            {
                type: 'pie',
                id: 'pie',
                radius: '30%',
                center: ['50%', '25%'],
                emphasis: {focus: 'data'},
                label: {
                    formatter: ': {@2012} (u0z1t8os%)'
                },
                encode: {
                    itemName: 'product',
                    value: '2012',
                    tooltip: '2012'
                }
            }
        ]
    };

    myChart.on('updateAxisPointer', function (event) {
        var xAxisInfo = event.axesInfo[0];
        if (xAxisInfo) {
            var dimension = xAxisInfo.value + 1;
            myChart.setOption({
                series: {
                    id: 'pie',
                    label: {
                        formatter: ': {@[' + dimension + ']} (u0z1t8os%)'
                    },
                    encode: {
                        value: dimension,
                        tooltip: dimension
                    }
                }
            });
        }
    });

    myChart.setOption(option);

});

if (option && typeof option === 'object') {
    myChart.setOption(option);
}

        </script>
    </body>
</html>
        '''
        ###########################################
        self.webview.setHtml(the_html_content)






################################################
#######程序入門
################################################
if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())



pyqt5和echarts的結(jié)合使用,再說明

綜上所述,如果有pyinstaller打包需求的,推薦大家使用pyqt5和echarts的結(jié)合使用。

echarts的圖表html模板,可以去官網(wǎng)的示例進行下載就可。官網(wǎng)很多示例的,需要哪個圖表模板,就點擊【下載示例】即可。

html的文本編輯,參數(shù)傳遞,就是最原始的字符串操作,這里就不細說了,基本操作嘛,就是繁瑣一點,但不復雜。

這里,展示一下我的一個餅圖html文本編輯,以供參考。

    #創(chuàng)建圖表
    def goto_creat_echarts_byhtml(self,all_datas):
        ##############################################
        the_html_content ='''
        <!DOCTYPE html>
        <html >
        <head>
            <meta charset="utf-8">
        </head>
        <body style="width:800px; height:300px;margin:auto;top:30px">
        <div id="container" style="width:800px; height:300px;margin:auto;top:30px"></div>

        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script>
        <script type="text/javascript"> 
                var dom = document.getElementById("container");
                var myChart = echarts.init(dom);
                var app = {};
                var option;
                option = {
                    tooltip: {
                        trigger: 'item',
                    },
                    title: {
                        text: '商城專遞員專遞單數(shù)',
                        left: 'left'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'right',
                    },'''


        #######設(shè)置##########################################################################
        the_html_content=the_html_content+'''series: ['''
        ############
        the_html_content =the_html_content + "{name: '專遞單數(shù)',type: 'pie',radius:'70%',emphasis: {itemStyle: {shadowBlur: 10,shadowOffsetX: 0,shadowColor: 'rgba(0, 0, 0, 0.5)'}},data:["
        for i in range(len(all_datas)):
            the_html_content = the_html_content+"{value:"  + str(all_datas[i][4]-all_datas[i][5])+", name: '"+ all_datas[i][3]+"-"+all_datas[i][1] + "'},"
        the_html_content = the_html_content+"]},"
        ############

        #######################################################################################

        the_html_content = the_html_content + ''']};
        if (option && typeof option === 'object') {myChart.setOption(option);}
        </script>
        </body>
        </html>
        '''

        #########################################################
        self.webview.setHtml(the_html_content)




本文如有幫助,敬請留言鼓勵。
本文如有錯誤,敬請留言改進。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容