Python+pyecharts繪制雙動態曲線教程詳解

總體跟官方樣例相似,但是官方樣例因為部分代碼有誤無法運行,同時需要瞭解json,以及前後端知識需要一些時間,因此供大傢參考。

這個是views

def line_base() -> Line:
    line = (
        Line()
        .add_xaxis(list(range(10)))
        .add_yaxis(series_name="專註度", y_axis=[randrange(0, 100) for _ in range(10)],areastyle_opts=opts.AreaStyleOpts(opacity=0.5))
        .add_yaxis(series_name="放松度", y_axis=[randrange(0, 100) for _ in range(10)],areastyle_opts=opts.AreaStyleOpts(opacity=0.5))
        .set_series_opts()
        .set_global_opts(
            title_opts=opts.TitleOpts(title="專註度和放松度"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value"),
        )
 
        .dump_options_with_quotes()
    )
    return line
 
class ChartView(APIView):
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(line_base()))
 
cnt = 9
cnt1 = 9
class ChartUpdateView(APIView):
    def get(self, request, *args, **kwargs):
        global cnt,cnt1
        cnt = cnt + 1
        cnt1 = cnt1 + 1
        return JsonResponse({"name": cnt,"value": randrange(0, 100),"name1":cnt1,"value1":randrange(0, 100)})

這個是urls界面

    path('index/',views.Index),
    path('line/', views.ChartView.as_view()),
    path('lineUpdate/', views.ChartUpdateView.as_view()),

html

function fetchData() {
            $.ajax({
                type: "GET",
                url: "http://127.0.0.1:8000/line",
                dataType: "json",
                success: function (result) {
                    var options = result.data;
                    line.setOption(options);
                    old_data = line.getOption().series[0].data;
                    old_data1 = line.getOption().series[1].data;
 
                }
            });
        }
 
function getDynamicData() {
            $.ajax({
                type: "GET",
                url: "http://127.0.0.1:8000/lineUpdate",
                dataType: 'json',
                success: function (result) {
                    var options = result.data;
                    old_data.push([options.name, options.value]);
                    old_data1.push([options.name1, options.value1]);
                    line.setOption({
                        series: [{
                            data: old_data
                        },
                        {
                           data:old_data1
                        }
                        ]
                    });
 
                }
            });
        }

效果如圖所示,這裡葉修改瞭Line圖的風格

到此這篇關於Python+pyecharts繪制雙動態曲線教程詳解的文章就介紹到這瞭,更多相關Python pyecharts雙動態曲線內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: