上海网站搭建平台公司,哈尔滨网络公司有哪些,一级造价工程师合格标准,python开发工具比较#xff08;八#xff09;利用python绘制指示器
指示器#xff08;Indicators#xff09;简介 指示器是一系列相关图的统称#xff0c;主要用于突出展示某一变量的实际值与目标值的差异#xff0c;例如常见的数据delta、仪表盘、子弹图、水滴图等。
快速绘制 基于p…比较八利用python绘制指示器
指示器Indicators简介 指示器是一系列相关图的统称主要用于突出展示某一变量的实际值与目标值的差异例如常见的数据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 gaugenumberdelta,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 numbergaugedelta, 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 numberdelta,value 40,))fig.update_layout(grid {rows: 2, columns: 2, pattern: independent},template {data : {indicator: [{title: {text: Speed},mode : numberdeltagauge,delta : {reference: 90}}]}})基于pyecharts 仪表盘只能居中无法改变位置。水球图可以通过center参数改变位置。 更多用法可以参考pyecharts-gallery from pyecharts import options as opts
from pyecharts.charts import Gauge, Liquid, Grid, Page# 创建仪表盘图表
g (Gauge().add(基本仪表盘, [(完成率, 66.6)],title_label_optsopts.GaugeTitleOpts(font_size20, offset_center[0,35]),detail_label_optsopts.GaugeDetailOpts(formatter{value}%, offset_center[0,60]),radius50%).set_global_opts(legend_optsopts.LegendOpts(is_showFalse),tooltip_optsopts.TooltipOpts(is_showTrue, formatter{a} br/{b} : {c}%))
)# 创建水球图
c (Liquid().add(lq, [0.6, 0.7], center[80%, 50%])
)# 在一个页面中显示两个图表调整每个图的宽度
grid (Grid().add(g, grid_optsopts.GridOpts(pos_left10%, pos_right55%)) .add(c, grid_optsopts.GridOpts(pos_left60%, pos_right10%))
)grid.render_notebook()基于matplotlib 参考Building a Bullet Graph in Python # 创建子弹图的函数
def bulletgraph(dataNone, limitsNone, labelsNone, axis_labelNone, titleNone,size(5, 3), paletteNone, formatterNone, target_colorgray,bar_colorblack, label_colorgray):data: 需要绘制的数据通常是一个二维列表列表的元素为三元组分别表示图例、目标值和实际值。例如[[图例A, 60, 75]]limits: 子弹图的分段标准例如[20, 60, 100] 表示图形将被分成 20, 20-60, 60-100 这几个区段labels: 子弹图中每个区段的名称axis_label: x轴的标签title: 图形标题size: 图形大小palette: 子弹图的颜色板formatter: 用于格式化x轴刻度的格式器target_color: 目标值线条的颜色默认是灰色bar_color: 实际值条形的颜色默认黑色label_color: 标签文本颜色默认灰色# 确定最大值来调整条形图的高度除以10似乎效果不错h limits[-1] / 10# 默认使用sns的绿色调色板if palette is None:palette sns.light_palette(green, len(limits), reverseFalse)# 如果只有一组数据创建一个子图否则根据数据的数量创建多个子图if len(data) 1:fig, ax plt.subplots(figsizesize, sharexTrue)else:fig, axarr plt.subplots(len(data), figsizesize, sharexTrue)# 针对每个子图添加一个子弹图条形for idx, item in enumerate(data):# 从创建的子图数组中获取轴对象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# 画出各个区段的柱形图for idx2, lim in enumerate(limits):ax.barh([1], lim - prev_limit, leftprev_limit, heighth,colorpalette[idx2]) prev_limit limrects ax.patches# 画出表示实际值的条形图ax.barh([1], item[1], height(h / 3), colorbar_color)# 计算y轴的范围确保目标线条的长度适应ymin, ymax ax.get_ylim()# 画出表示目标值的线条ax.vlines(item[2], ymin * .9, ymax * .9, linewidth1.5, colortarget_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, hacenter, vabottom, colorlabel_color) # 设置x轴刻度的格式if formatter:ax.xaxis.set_major_formatter(formatter)# 设置x轴的标签if axis_label:ax.set_xlabel(axis_label)# 设置子图的标题if title:fig.suptitle(title, fontsize14)# 调整子图之间的间隔fig.subplots_adjust(hspace0) 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)
# 通过自定义函数格式化刻度值
money_fmt FuncFormatter(money)# 自定义数据
data [(HR, 50000, 60000),(Marketing, 75000, 65000),(Sales, 125000, 80000),(RD, 195000, 115000)]
# 自定义颜色
palette sns.light_palette(grey, 3, reverseFalse)# 绘制子弹图
bulletgraph(data, limits[50000, 125000, 200000],labels[Below, On Target, Above], size(10,5),axis_label年终预算, label_colorblack,bar_color#252525, target_color#f7f7f7, palettepalette,title营销渠道预算绩效,formattermoney_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 [, bVery high/b, bHigh/b, bMedium/b, bLow/b, bVery 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[# 半圆型饼图构造仪表盘go.Pie(values[0.5] (np.ones(n_quadrants) / 2 / n_quadrants).tolist(),rotation90,hole0.5,marker_colorsquadrant_colors,textquadrant_text,textinfotext,hoverinfoskip,),],layoutgo.Layout(showlegendFalse,margindict(b0,t10,l10,r10),width450,height450,paper_bgcolorplot_bgcolor,# 注释annotations[go.layout.Annotation(textfSpeed Now: {current_value},x0.5, xanchorcenter, xrefpaper,y0.4, yanchorbottom, yrefpaper,showarrowFalse,)],# 指针shapes[# 圆点go.layout.Shape(typecircle,x00.48, x10.48,y00.52, y10.52,fillcolor#333,line_color#333,),# 线go.layout.Shape(typeline,x00.5, x10.5 hand_length * np.cos(hand_angle),y00.5, y10.5 hand_length * np.sin(hand_angle),linedict(color#333, width4))])
)
fig.show()总结
以上通过plotly、pyecharts和matplotlib绘制了各种各样的指示器。也利用plotly通过自定义方式模拟出仪表盘的效果。
共勉