简介
Plotly 是一个非常强大的开源数据可视化框架,它通过构建基于 HTML 的交互式图表来显示信息,可创建各种形式的精美图表。本文所说的 Plotly 指的是 Plotly.js 的 Python 封装,plotly本身是个生态非常复杂的绘图工具,它对很多编程语言提供接口。交互式和美观易用应该是 Plotly 最大的优势,而 Matplotlib 的特点则是可定制化程度高,但语法也相对难学,各有优缺点。
安装及开发工具
安装通过 PIP 进行即可。
pip install plotly
Plotly Python 其对应的官网为Plotly Python Graphing Library,上面有一些教程和官方API接口的查询。
三维动态绘图
Plotly二大优势:1、自带交互式按钮,可用鼠标点击,拖动十分便捷。但需要注意若没有显卡驱动可能无法打开文件,如图中所示错误,此时需要安装更新显卡驱动,如图所示。
2、可以生成html文件,便于在各个电脑使用。
plotly绘制三维图需调用go.Scatter3d函数
#以下代码绘制静态图 data = [] trace = go.Scatter3d(x=, y=, z=, mode="lines", line=dict(color='orange'), name='XXX' + str(i + 1), opacity=0.7) data.extend([trace])
x y z分别为对应坐标,mode为类型包括线性lines 散点型markers等等,需要根据具体情况具体使用,name为名称,opacity为透明度范围0~1。
#以下代码为绘制动态图 frames = [] for i in range(m): trace = go.Scatter3d(x=, y=, z=, mode="lines", line=dict(color='orange'),name='', opacity=0.8) data.insert(0, trace) ###这里用来补充线,否则绘制动图时,会消失 for k in range(Page): a = [] a = [go.Surface(x=, y=, z=, showscale=False, colorscale=colorscale2[k], opacity=0.5,name='填充区域',surfacecolor=SurfaceColor2[k])] ###这里 frame = [go.Frame(data=a, name=str(k))] frames.extend(frame)
这里为在静态图基础上绘制动态区域,需要对frams进行数据补充。
#生成图像所需数据 fig = go.Figure(data=data, frames=frames) #滑块配置 steps = [] for k, f in enumerate(fig.frames): # print(str(k), f.name) step = dict( method="animate", label=str(atime[k]), args=[[f.name], frame_args(20)], ) steps.append(step) sliders = [dict( active=0, # 默认值 currentvalue={"prefix": "时间/μs:"}, # 滑动条显示的名称; pad={"b": 20, "t": 10}, # 调节滑动条的位置,单位像素; steps=steps )]
#图层配置 fig.update_layout( # title='Slices in volumetric data', # width=1200, # height=1200, # scene=dict( # zaxis=dict(range=[0, 1200], autorange=False), # aspectratio=dict(x=1, y=1, z=1), # ), hovermode="closest", updatemenus=[ { "buttons": [ { "args": [None, frame_args(-1.5)], "label": "▶", # play symbol "method": "animate", }, # { # "args": [[None], frame_args(0)], # "label": "◼", # pause symbol # "method": "animate", # }, ], "direction": "left", "pad": {"r": 10, "t": 60}, "type": "buttons", "x": 0, "xanchor": "right", "y": 0, "yanchor": "top", } ], showlegend=True, #是否显示标注 sliders=sliders,#滑块初始化 scene=dict(camera=dict(eye=dict(x=POIN1Z[0], y=POIN1Z[1], z=POIN1Z[2]),up=dict(x=1,y=0,z=0)))#eye视角配置 up选择哪个坐标轴朝上 ) picture = py.plot(fig,filename='XXX.html',auto_open=False)
showlegend=True, #是否显示标注,
filename生成的html文件名;
auto_open是否自动打开文件。