Plotly(一) —— 配置项&图表类型

Plotly(一) —— 配置项&图表类型

大家可以关注知乎或微信公众号的share16,我们也会同步更新此文章。

   Plotly官网

   关于Plotly的内容 1

一、Plotly简介

   对数据的分析离不开数据的可视化,相对于Python在数据分析、人工智能、量化投资等领域中的发展,在数据可视化方面的发展有些滞后。最经典的Python可视化绘图库莫过于 Matplotlib了;为了绘出更漂亮的图像,Python开源社区开发出了Seaborn绘图模块,它本质上是对 Matplotlib的封装,绘图效果更符合现代人的审美观。

  • 就使用的经验而言,Matplotlib主要存在两大缺陷:
    • Matplotlib是一个静态的绘图模块,即我们绘出的图像是静态的,就像用看图软件打开图片一样,没有网页绘图的交互式效果;
    • Matplotlib绘图结果的分享很不方便,在绘图结果分享给别人时只能以图片的方式分享,别人看到的绘图结果完全是静态的,分享体验很不好;
  • Matplotlib一直以来都是Python可视化的主力军,但是确实存在无法克服的缺陷,并且其他的Python绘图模块如Ggplot、Bokeh、Pygal等都比较小众,绘图功能比较单一,完成不了对Matplotlib的替代。

   为了解决 Python在可视化中存在的问题, Plotly 应运而生,它是一个基于JavaScript的动态绘图模块。Plotly的绘图效果与我们在网页上看到的动态交互式绘图效果是一样的,其默认的绘图结果是一个HTML网页文件,通过浏览器就可以查看。我们可以把这个HTML文件分享给其他人,对方看到的效果与我们在本机上看到的效果完全一样。Plotly在绘图模块上是Matplotlib强有力的竞争对手,Plotly绘图的种类丰富、效果美观、易于保存与分享,因而越来越受数据分析人士的喜爱。

   Plotly绘图底层使用的是plotly.js,plotly.js基于D3.js、stack.gl和SVG,用JavaScript在网页上实现类似MATLAB和Matplotlib的图形展示功能,支持数十种图形,包括2D和3D图形,交互流畅,可以满足一般科学计算的需要。目前已经有Python、MATLAB、R语言、Jupyter等多种版本的API接口。

   Plotly绘图模块库可直接生成PNG等图像文件,与Bokeh绘图模块库和各种基于Web的JavaScript图表模块库类似,生成的是一个内置JavaScript脚本的HTML网页文件,虽然文件比Bokeh绘图模块库生成的文件略大,但在互动性方面,Plotly绘图模块库强大得多。

  • Plotly的内置信息

    • 内置数据集,如px.data.gapminder();
    • 内置颜色面板,如px.colors.carto.swatches() 、px.colors.sequential.swatches();

  • Plotly的基本绘图流程

    • 添加图轨数据(add_trace),使用的是Scatter等函数命令;
    • 设置画面布局,使用layout命令;
    • 集成图形、布局数据,命令有Data、Figure;
    • 绘制图形的输出;

  • Plotly的离线绘图功能 允许在没有网络的情况下绘图,并把图像保存到本地。

    • init_notebook_mode(connected=False) :默认False,plotly.js库将从本地plotly加载;若为True,plotly.js库将从在线CDN加载;
    • plotly.offline.plot() :在本地新建一个HTML文件,并可以选择是否在浏览器中打开这个文件;
    • plotly.offline.iplot() :在Jupyter中直接绘图,而不需要新建一个HTML文件;
    • 参数解读
      • show_link:是否显示右下角的链接,默认为False;
      • link_text:右下角文字,默认为Export to plot.ly;
      • validate:默认为True,确保所有关键字是有效的;
      • filename:设置绘图结果的存储路径;
      • image:默认为None,表示不下载图片;还可取值为png/jpeg/svg/webp,表示下载图片的格式;

二、Plotly基础图形

2.1 散点图

  • 参数解读
    • mode:默认None,取值范围有markers、lines、lines+markers、text等;
    • opacity:透明度参数,范围时是0~1;
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
from plotly.subplots import make_subplots #子图
from plotly.offline import init_notebook_mode,iplot,plot #初始化、绘图

init_notebook_mode(connected=False)
df = pd.DataFrame({'x':[1,2,3,4,5],'y1':[22,30,27,32,30],'y2':[26,31,32,33,32]})
trace1 = go.Scatter(x=df.x,y=df.y1,mode='markers',name='y1',marker={'symbol':'square'})
trace2 = go.Scatter(x=df.x,y=df.y2,mode='markers',name='y2',marker={'symbol':'circle'})
trace = [trace1,trace2]


layout = {'title':{'text':'<b>散点图</b>','x':0.5,'font':{'color':'red','size':26}},
          'showlegend':False}

fig = make_subplots(rows=1,cols=3,subplot_titles=['express','graph_objects','add_scatter'])

fig.add_trace(px.scatter(data_frame=df,x='x',y='y1',symbol_sequence=['square']).data[0],row=1,col=1)
fig.add_trace(px.scatter(data_frame=df,x='x',y='y2',symbol_sequence=['circle']).data[0],row=1,col=1)

fig.add_trace(trace1,row=1,col=2)
fig.add_trace(trace2,row=1,col=2)

fig.add_scatter(x=df.x,y=df.y1,mode='markers',name='y1',row=1,col=3)
fig.add_scatter(x=df.x,y=df.y2,mode='markers',name='y2',row=1,col=3)

fig.update_layout(layout)

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

2.2 线形图

init_notebook_mode(connected=False)
df = pd.DataFrame({'x':[1,2,3,4,5],'y1':[22,30,27,32,30],'y2':[26,31,32,33,32]})
trace1 = go.Scatter(x=df.x,y=df.y1,mode='lines+markers',name='y1',
                    marker={'symbol':'square'},line={'dash':'solid','shape':'linear'})
trace2 = go.Scatter(x=df.x,y=df.y2,mode='lines+markers',name='y2',
                    marker={'symbol':'circle'},line={'dash':'dashdot','shape':'spline'})
trace = [trace1,trace2]


layout = {'title':{'text':'<b>线形图</b>','x':0.5,'font':{'color':'red','size':26}},
          'showlegend':False}

fig = make_subplots(rows=1,cols=3,subplot_titles=['express','graph_objects','add_scatter'])


fig.add_trace(px.line(data_frame=df,x='x',y='y1',line_dash_sequence=['solid'],line_shape='linear',\
                      markers=True,symbol_sequence=['square']).data[0],row=1,col=1)
fig.add_trace(px.line(data_frame=df,x='x',y='y2',line_dash_sequence=['dot'],line_shape='spline',\
                      markers=True,symbol_sequence=['circle']).data[0],row=1,col=1)

fig.add_trace(trace1,row=1,col=2)
fig.add_trace(trace2,row=1,col=2)

fig.add_scatter(x=df.x,y=df.y1,mode='lines+markers',name='y1',row=1,col=3)
fig.add_scatter(x=df.x,y=df.y2,mode='lines+markers',name='y2',row=1,col=3)

fig.update_layout(layout)

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

2.3 柱状图/条形图

   条形图 是由柱状图修改参数(即orientation=‘h’)而来的。

  • 参数解读
    • base:柱状图的起始参数;
    • orientation:图形显示方向,包括v(垂直)和h(水平);
    • barmode:取值stack、relative、group、overlay;使用go.Bar时,只能在go.Layout中定义这个参数;而使用px.bar时,此函数中就有这个参数;
init_notebook_mode(connected=False)
df = pd.DataFrame({'x':[1,2,3,4,5],'y1':[22,30,27,32,30],'y2':[26,31,32,33,32]})
trace1 = go.Bar(x=df.x,y=df.y1,name='y1')
trace2 = go.Bar(x=df.x,y=df.y2,name='y2')
trace = [trace1,trace2]

layout = {'title':{'text':'<b>柱状图</b>','x':0.5,'font':{'color':'red','size':26}},
          'showlegend':False,
          'barmode':'stack'}

fig = make_subplots(rows=1,cols=3,subplot_titles=['express','graph_objects','add_bar'])

fig.add_trace(px.bar(data_frame=df,x='x',y='y1',color_discrete_sequence=['orange']).data[0],row=1,col=1)
fig.add_trace(px.bar(data_frame=df,x='x',y='y2',color_discrete_sequence=['lightskyblue']).data[0],row=1,col=1)

fig.add_trace(trace1,row=1,col=2)
fig.add_trace(trace2,row=1,col=2)

fig.add_bar(x=df.x,y=df.y1,name='y1',row=1,col=3)
fig.add_bar(x=df.x,y=df.y2,name='y2',row=1,col=3)

fig.update_layout(layout)

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

2.4 饼图/环形饼图

   Pie函数中最常用的两个属性一个是values,用于赋给其需要可视化的数据;另一个是labels,表示不同数据对应的标签;绘制环形饼图,只需在Pie函数中设置控制环形中心空白大小的hole属性即可实现。
   在子图中,绘制饼图时,要对子图进行设置(即参数specs),子图默认的type是xy,要修正为pie,代码如下。

  • 参数解读
    • rotation:扇区旋转角度,默认0(12点位置),取值范围是0~360;
    • direction:饼图方向,默认counterclockwise(逆时针),还可取值为clockwise(顺时针);
    • hole:环形饼图内径孔的半径,默认0,取值范围是0~1;
    • pull:组成饼图的各个扇形的突出程度,默认0(即不突出),取值范围是0~1;
    • textinfo:在扇形上显示的内容样式,取值范围有label、value、percent等;使用px.pie时,只能在fig.update_traces中定义这个参数;而使用go.Pie时,此函数中就有这个参数;
init_notebook_mode(connected=False)
df = pd.DataFrame({'x':[1,2,3,4,5],'y1':[22,30,27,32,30],'y2':[26,31,32,33,32]})
trace1 = go.Pie(labels=df.x,values=df.y1)
trace = [trace1]


layout = {'title':{'text':'<b>饼图</b>','x':0.5,'font':{'color':'red','size':26}},
          'showlegend':False}

fig = make_subplots(rows=1,cols=3,subplot_titles=['express','graph_objects','add_pie'],
                    specs=[[{'type':'pie'},{'type':'pie'},{'type':'pie'}]])

fig.add_trace(px.pie(data_frame=df,labels='x',values='y1').data[0],row=1,col=1)

fig.add_trace(trace1,row=1,col=2)

fig.add_pie(labels=df.x,values=df.y1,textinfo='label+percent',row=1,col=3)

fig.update_traces(textinfo='label+percent',textposition='inside')
fig.update_layout(layout)

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

2.5 热力图

   构建热力图的方法有:go.Heatmap、px.imshow、px.density_heatmap、plotly.figure_factory.create_annotated_heatmap。

  • 参数解读
    • 显示数据:Heatmap使用参数texttemplate,imshow、density_heatmap使用参数text_auto;
    • 设置颜色:Heatmap使用参数colorscale,imshow、density_heatmap使用Layout中的参数colorscale-sequential;
    • 不显示颜色条:Heatmap使用参数showscale,imshow、density_heatmap使用Layout中的参数coloraxis-showscale;
init_notebook_mode(connected=False)
df = pd.DataFrame({'x':[1,2,3,4,5],'y1':[22,30,27,32,30],'y2':[26,31,32,33,32]})
df1 = df.corr()
trace1 = go.Heatmap(x=df1.index,y=df1.columns,z=df1,texttemplate='%{z:.2f}',
                    colorscale='greens',showscale=False)



layout = {'title':{'text':'<b>热力图</b>','x':0.5,'font':{'color':'red','size':26}}}

fig = make_subplots(rows=1,cols=3,subplot_titles=['express','graph_objects','add_heatmap'])

fig.add_trace(px.imshow(df1,text_auto='.2f').data[0],row=1,col=1)
fig.update_layout(colorscale={'sequential':'sunset'},coloraxis={'showscale':False})

fig.add_trace(trace1,row=1,col=2)

fig.add_heatmap(x=df1.index,y=df1.columns,z=df1,texttemplate='%{z:.2f}',
                colorscale='rainbow',showscale=False,row=1,col=3)

fig.update_layout(layout)

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

init_notebook_mode(connected=False)
df = pd.DataFrame({'x':[1,2,3,4,5],'y1':[22,30,27,32,30],'y2':[26,31,32,33,32]})
df1 = df.corr().stack().reset_index()
df1.columns = ['left','right','value']


layout = {'title':{'text':'<b>热力图:px.density_heatmap</b>','x':0.5,'font':{'color':'red','size':26}},
          'colorscale':{'sequential':'sunset'}, 
          # density_heatmap函数 可设置参数color_continuous_scale
          'coloraxis':{'showscale':False}}

px.density_heatmap(data_frame=df1,x='left',y='right',z='value',text_auto='.2f',
                   template={'layout':layout})

在这里插入图片描述

2.6 点地图

   构建点地图的方法有:go.Scattergeo、px.scatter_geo;此外,地图函数还有go.Scattermapbox、go.Choropleth、px.scatter_mapbox、px.choropleth等等。

  • 参数解读
    • 根据 fig.data 中 geo键对应的值,设置projection(rotation旋转);
init_notebook_mode(connected=False)
df = pd.read_csv('XXX/directory.csv',encoding='gbk')
trace = go.Scattergeo(lat=df.Latitude,lon=df.Longitude,text=df[['Store Name','Ownership Type']])

layout = {'title':{'text':'<b>点地图</b>','x':0.5,'font':{'color':'red','size':26}},
          
          #根据fig.data中geo键对应的值,设置projection(rotation旋转)
          'geo2':{'projection':{'rotation':{'lat':30,'lon':110}}},
          
          'geo3':{'projection':{'type':'orthographic',
                                'rotation':{'lat':30,'lon':110}}},
          'showlegend':False}

fig = make_subplots(rows=1,cols=3,subplot_titles=['express','graph_objects','add_scattergeo'],
                    specs=[[{'type':'scattergeo'},{'type':'scattergeo'},{'type':'scattergeo'}]])

fig.add_trace(px.scatter_geo(data_frame=df,lat='Latitude',lon='Longitude',
                             hover_name='City',hover_data=['Store Name','Ownership Type']).data[0],
              row=1,col=1)

fig.add_trace(trace,row=1,col=2)

fig.add_scattergeo(lat=df.Latitude,lon=df.Longitude,row=1,col=3)

fig.update_layout(layout)

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

三、Plotly高级图形

   在Plotly中,animation_frameanimation_group用于控制动画的效果。这两个参数通常一起使用,可以创建更加丰富的动画效果。例如,在时间序列数据的折线图中,可以使用animation_frame参数来控制每一帧所显示的时间点,而使用animation_group参数来控制不同数据序列的动画效果。
   此外,px.scatter、px.line、px.bar等函数中有这两个参数。

3.1 时间序列-时间线轮播图

  • 参数解读
    • animation_frame:表示动画帧的数量,它通常用于时间序列数据或者三维图形的动画中,表示动画中每一帧的索引或者名称。通过设置此参数,你可以控制动画中每一帧所显示的内容;
    • animation_group:表示动画的分组方式,它通常用于多个数据序列的动画中,可以将数据序列按照不同的分组方式进行动画展示。通过设置此参数,你可以控制同一组动画中不同数据序列的动画效果;
init_notebook_mode(connected=False)
df = px.data.gapminder()

layout = {'title':{'text':'<b>时间线轮播图</b>','x':0.5,'font':{'color':'red','size':26}}}

fig = px.scatter(data_frame=df,x='gdpPercap',y='lifeExp',size='pop',size_max=55,
                 color='continent',hover_name='country',log_x=True,range_x=[100,100000],
                 range_y=[25,90],animation_frame='year',animation_group='country')

fig.update_layout(layout)
fig['layout'].pop('updatemenus') #删除 animation buttons

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

3.2 时间序列-滑块和选择器

  • 参数解读
    • rangeslider:滑块;rangeselector:选择器;
    • step:rangeselector参数,取值范围month、year、day、hour、minute、second、all;例如“count=1,step=‘month’”时,这个选择器覆盖的时间长度是(1*month),即一个月;
    • stepmode:rangeselector参数,取值范围backward、todate;例如①当取值backward时,表示从后往前推进(count*step)时间,即当“count=1,step=‘year’”时,表示时间范围将近一年;②当取值todate时,就是计算今年以来的时间,即从最后日期到最后日期所在的年初,而不是近一年;
init_notebook_mode(connected=False)
df = pd.read_csv('XXX/s.csv',encoding='gbk',parse_dates=['开奖日期'])
df = df.iloc[:,1:10]


'''滑块 : rangeslider , 选择器 : rangeselector'''

layout = {'title':{'text':'<b>时间序列</b>',
                   'x':0.5,
                   'font':{'color':'red','size':26}},
          'xaxis':{'tickformat':'%Y-%m-%d',
                   'range':[df.开奖日期.min().replace(day=1),
                            df.开奖日期.max().replace(day=df.开奖日期.max().daysinmonth)],
                   'rangeselector':{'x':0.2,
                                    'buttons':[{'label':'近一年','count':1,'step':'year','stepmode':'backward'},
                                               {'label':'今年','count':1,'step':'year','stepmode':'todate'},
                                               {'label':'近一月','count':1,'step':'month','stepmode':'backward'},
                                               {'label':'all','step':'all'}]},
                   'rangeslider':{'visible':False}}}

fig = px.line(data_frame=df,x='开奖日期',y='蓝球',line_dash_sequence=['solid'],
              markers=False,symbol_sequence=['circle'])

fig.update_layout(layout)

#plot(fig,image=None,filename='temp-plot.html')
iplot(fig,image=None,filename='plot_image')

在这里插入图片描述

3.3 其他图形

import plotly.figure_factory as ff
    • 等高线图:px.density_contour;
    • 散点矩阵图:px.scatter_matrix;
    • 并行分类图:px.parallel_categories;
    • 联合分布图:px.scatter,涉及的参数有:marginal_x、marginal_y;
    • 热力图:ff.create_annotated_heatmap;
    • 甘特图:ff.create_gantt;
    • 表格:ff.create_table;

谢谢大家 🌹



  1. 关于Plotly的内容,来源于《Python数据分析:基于Plotly的动态可视化绘图》

    ↩︎

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值