淘寶做基礎(chǔ)銷量怎么網(wǎng)站企業(yè)類網(wǎng)站有哪些例子
比較(八)利用python繪制指示器
指示器(Indicators)簡介
指示器是一系列相關(guān)圖的統(tǒng)稱,主要用于突出展示某一變量的實際值與目標值的差異,例如常見的數(shù)據(jù)delta、儀表盤、子彈圖、水滴圖等。
快速繪制
-
基于plotly
更多用法可參考Indicators in Python
import plotly.graph_objects as gofig = go.Figure()# 自定義儀表盤 fig.add_trace(go.Indicator(domain = {'row': 0, 'column': 0},value = 450,mode = "gauge+number+delta",title = {'text': "Speed"},delta = {'reference': 380},gauge = {'axis': {'range': [None, 500]},'steps' : [{'range': [0, 250], 'color': "lightgray"},{'range': [250, 400], 'color': "gray"}],'threshold' : {'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 490}}))# 自定義子彈圖 fig.add_trace(go.Indicator(domain = {'x': [0.05, 0.5], 'y': [0.15, 0.35]},mode = "number+gauge+delta", value = 180,delta = {'reference': 200},gauge = {'shape': "bullet",'axis': {'range': [None, 300]},'threshold': {'line': {'color': "black", 'width': 2},'thickness': 0.75,'value': 170},'steps': [{'range': [0, 150], 'color': "gray"},{'range': [150, 250], 'color': "lightgray"}],'bar': {'color': "black"}}))# 基本delta fig.add_trace(go.Indicator(domain = {'row': 0, 'column': 1},mode = "delta",value = 300,))# 自定義delta fig.add_trace(go.Indicator(domain = {'row': 1, 'column': 1},mode = "number+delta",value = 40,))fig.update_layout(grid = {'rows': 2, 'columns': 2, 'pattern': "independent"},template = {'data' : {'indicator': [{'title': {'text': "Speed"},'mode' : "number+delta+gauge",'delta' : {'reference': 90}}]}})
-
基于pyecharts
儀表盤只能居中,無法改變位置。水球圖可以通過center參數(shù)改變位置。
更多用法可以參考pyecharts-gallery
from pyecharts import options as opts from pyecharts.charts import Gauge, Liquid, Grid, Page# 創(chuàng)建儀表盤圖表 g = (Gauge().add("基本儀表盤", [("完成率", 66.6)],title_label_opts=opts.GaugeTitleOpts(font_size=20, offset_center=[0,35]),detail_label_opts=opts.GaugeDetailOpts(formatter='{value}%', offset_center=[0,60]),radius="50%").set_global_opts(legend_opts=opts.LegendOpts(is_show=False),tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{a} <br/> : {c}%")) )# 創(chuàng)建水球圖 c = (Liquid().add("lq", [0.6, 0.7], center=["80%", "50%"]) )# 在一個頁面中顯示兩個圖表,調(diào)整每個圖的寬度 grid = (Grid().add(g, grid_opts=opts.GridOpts(pos_left="10%", pos_right="55%")) .add(c, grid_opts=opts.GridOpts(pos_left="60%", pos_right="10%")) )grid.render_notebook()
-
基于matplotlib
參考:Building a Bullet Graph in Python
# 創(chuàng)建子彈圖的函數(shù) def bulletgraph(data=None, limits=None, labels=None, axis_label=None, title=None,size=(5, 3), palette=None, formatter=None, target_color="gray",bar_color="black", label_color="gray"):'''data: 需要繪制的數(shù)據(jù),通常是一個二維列表,列表的元素為三元組,分別表示圖例、目標值和實際值。例如:[["圖例A", 60, 75]]limits: 子彈圖的分段標準,例如:[20, 60, 100] 表示圖形將被分成 <20, 20-60, >60-100 這幾個區(qū)段labels: 子彈圖中每個區(qū)段的名稱axis_label: x軸的標簽title: 圖形標題size: 圖形大小palette: 子彈圖的顏色板formatter: 用于格式化x軸刻度的格式器target_color: 目標值線條的顏色,默認是灰色bar_color: 實際值條形的顏色,默認黑色label_color: 標簽文本顏色,默認灰色'''# 確定最大值來調(diào)整條形圖的高度(除以10似乎效果不錯)h = limits[-1] / 10# 默認使用sns的綠色調(diào)色板if palette is None:palette = sns.light_palette("green", len(limits), reverse=False)# 如果只有一組數(shù)據(jù),創(chuàng)建一個子圖;否則,根據(jù)數(shù)據(jù)的數(shù)量創(chuàng)建多個子圖if len(data) == 1:fig, ax = plt.subplots(figsize=size, sharex=True)else:fig, axarr = plt.subplots(len(data), figsize=size, sharex=True)# 針對每個子圖,添加一個子彈圖條形for idx, item in enumerate(data):# 從創(chuàng)建的子圖數(shù)組中獲取軸對象if len(data) > 1:ax = axarr[idx]# 格式設置,移除多余的標記雜項ax.set_aspect('equal')ax.set_yticks([1])ax.set_yticklabels([item[0]])ax.spines['bottom'].set_visible(False)ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.spines['left'].set_visible(False)prev_limit = 0# 畫出各個區(qū)段的柱形圖for idx2, lim in enumerate(limits):ax.barh([1], lim - prev_limit, left=prev_limit, height=h,color=palette[idx2]) prev_limit = limrects = ax.patches# 畫出表示實際值的條形圖ax.barh([1], item[1], height=(h / 3), color=bar_color)# 計算y軸的范圍,確保目標線條的長度適應ymin, ymax = ax.get_ylim()# 畫出表示目標值的線條ax.vlines(item[2], ymin * .9, ymax * .9, linewidth=1.5, color=target_color) # 添加標簽if labels is not None:for rect, label in zip(rects, labels):height = rect.get_height()ax.text(rect.get_x() + rect.get_width() / 2, -height * .4, label, ha='center', va='bottom', color=label_color) # 設置x軸刻度的格式if formatter:ax.xaxis.set_major_formatter(formatter)# 設置x軸的標簽if axis_label:ax.set_xlabel(axis_label)# 設置子圖的標題if title:fig.suptitle(title, fontsize=14)# 調(diào)整子圖之間的間隔fig.subplots_adjust(hspace=0)
import matplotlib.pyplot as plt import seaborn as sns from matplotlib.ticker import FuncFormatter import matplotlib as mplplt.rcParams['font.sans-serif'] = ['SimHei'] # 用來正常顯示中文標簽# 格式化為貨幣 def money(x, pos):return "${:,.0f}".format(x) # 通過自定義函數(shù)格式化刻度值 money_fmt = FuncFormatter(money)# 自定義數(shù)據(jù) data = [("HR", 50000, 60000),("Marketing", 75000, 65000),("Sales", 125000, 80000),("R&D", 195000, 115000)] # 自定義顏色 palette = sns.light_palette("grey", 3, reverse=False)# 繪制子彈圖 bulletgraph(data, limits=[50000, 125000, 200000],labels=["Below", "On Target", "Above"], size=(10,5),axis_label="年終預算", label_color="black",bar_color="#252525", target_color='#f7f7f7', palette=palette,title="營銷渠道預算績效",formatter=money_fmt)
定制多樣化的指示器
參考:Gauge Chart with Python
利用plotly模擬儀表盤
import plotly.graph_objects as go
import numpy as npplot_bgcolor = "white"
quadrant_colors = [plot_bgcolor, "#f25829", "#f2a529", "#eff229", "#85e043", "#2bad4e"]
quadrant_text = ["", "<b>Very high</b>", "<b>High</b>", "<b>Medium</b>", "<b>Low</b>", "<b>Very low</b>"]
n_quadrants = len(quadrant_colors) - 1current_value = 450
min_value = 0
max_value = 600
# 指針長度
hand_length = np.sqrt(2) / 4
# 指針角度
hand_angle = np.pi * (1 - (max(min_value, min(max_value, current_value)) - min_value) / (max_value - min_value))fig = go.Figure(data=[# 半圓型餅圖構(gòu)造儀表盤go.Pie(values=[0.5] + (np.ones(n_quadrants) / 2 / n_quadrants).tolist(),rotation=90,hole=0.5,marker_colors=quadrant_colors,text=quadrant_text,textinfo="text",hoverinfo="skip",),],layout=go.Layout(showlegend=False,margin=dict(b=0,t=10,l=10,r=10),width=450,height=450,paper_bgcolor=plot_bgcolor,# 注釋annotations=[go.layout.Annotation(text=f"Speed Now: {current_value}",x=0.5, xanchor="center", xref="paper",y=0.4, yanchor="bottom", yref="paper",showarrow=False,)],# 指針shapes=[# 圓點go.layout.Shape(type="circle",x0=0.48, x1=0.48,y0=0.52, y1=0.52,fillcolor="#333",line_color="#333",),# 線go.layout.Shape(type="line",x0=0.5, x1=0.5 + hand_length * np.cos(hand_angle),y0=0.5, y1=0.5 + hand_length * np.sin(hand_angle),line=dict(color="#333", width=4))])
)
fig.show()
總結(jié)
以上通過plotly、pyecharts和matplotlib繪制了各種各樣的指示器。也利用plotly通過自定義方式模擬出儀表盤的效果。
共勉~