plotly for python 使用教程

安装

pip install plotly复制代码

代码整体结构

#plotly for python (offline)
import plotly.offline as ptly
import plotly.graph_objs as go
data=[]
trace1 = go.Bar(PlotlyDict)            #图形属性设置(Bar为柱状图)
data.append(trace1)
trace2 = go.Bar(PlotlyDict)                  
data.append(trace2)
layout = go.Layout(PlotlyDict)             #布局属性设置
fig = go.Figure(data=data, layout=layout)
ptly.plot(fig, filename = '文件名.html')   #图像整体属性设置复制代码

示例:

import plotly.offline as ptly
import plotly.graph_objs as go
data=[]
trace1 = go.Bar(x=['first','second','third'],
                y=[20,40,30]
    )       
data.append(trace1)
layout = go.Layout(font=dict(family='Courier New, monospace', size=18, color='#3D3D3D'), 
                   title='example'
    )           
fig = go.Figure(data=data, layout=layout)
ptly.plot(fig, filename = 'example.html')复制代码

注:(1)trace也可表示为以下形式

trace1 = {'type':'bar',
          'x':['first','second','third'],
          'y':[20,40,30]
    }复制代码

​ (2)go.Layout、go.Figure都可用dict代替

图形属性

柱状图:

trace1 = go.Bar(x=[],
                y=[],
                name='thename',
                width=0.5,
                marker=dict(color="#c45ca2"),
                opacity=1
            )复制代码

饼图:

trace1 = go.Pie(labels=[],
                values=[],
                hoverinfo='label+percent', 
                textinfo='value', 
                textfont=dict(size=20),
                marker=dict(colors=colors, 
                           line=dict(color='#000000', width=2)),
                hole= .4,
                name="pie name",
                domain=dict(x = [0, .48]),
                opacity=1
            )复制代码

散点图/折线图:

trace1 = go.Scatter(x = [],
                    y = [],
                    mode = 'markers',   #mode可选'markers','lines','lines+markers'
                    name = 'the name',
                    marker = dict(size = 10,        #若设为变量则可用散点大小表示变量大小
                                  color = 'rgba(152, 0, 0, .8)',
                                  line = dict(width = 2,
                                              color = 'rgb(0, 0, 0)'
                                              ),
                                  opacity=[]
                                )
            )复制代码

布局属性

通用:

layout = go.Layout(title='your title',  #大标题 
                   font=dict(
                     family='Courier New, monospace',
                     size=18, 
                     color='#3D3D3D'
                               ),#字体
                   width=1400,
                   height=800,              #图形的大小
                   margin=go.Margin(
                                    l=100,
                                    r=100,
                                    b=200,
                                    t=200,
                                    pad=0
                                    ),      #边距设置
                   plot_bgcolor='#ffffff',   #绘图部分背景颜色
                   paper_bgcolor='#ffffff',   #整体背景颜色
                   showlegend=True,        #是否显示图例,也可放在每个trace里单独设置
                   #图例相关参数设置:
                   legend=dict(orientation="v",
                                x=0,
                                y=1,
                                traceorder='normal',
                                font=dict(
                                        family='sans-serif',
                                        size=12,
                                        color='#000'
                                            ),
                                bgcolor='#E2E2E2',
                                bordercolor='#FFFFFF',
                                borderwidth=2
                            ),    
                   #x轴相关参数设置(y轴对应yaxis):
                   xaxis=dict(title='x Axis',
                              titlefont=dict(
                                        family='Courier New, monospace',
                                        size=18,
                                        color='#7f7f7f'
                                            ),
                               range=[],   #x轴范围,如[0,30]
                               type='-',  
                              #x轴类型,可选["-","linear","log","date","category"] 
                               domain=[0,0.45] 
                              #设置x轴在整个图像占的位置范围(主要在有多张图时使用,第二个图用xaxis2设置相关参数)        
                            )                   
    )复制代码

柱状图:

layout = go.Layout(bargap=0.3,      #0~1
                   bargroupgap=0.1,  #0~1
                   barmode='',    
                   #barmode: ["stack","group","overlay","relative"],设置多个trace的组合方式
                   barnorm=''
    )复制代码

图像整体属性

ptly.plot(figure_or_data, show_link=True, link_text='Export to plot.ly',
         validate=True, output_type='file', include_plotlyjs=True,
         filename='temp-plot.html', auto_open=True, image=None,
         image_filename='plot_image', image_width=800, image_height=600,
         config=None)复制代码

数据处理

包括aggregate,filter,groupby,sort

在trace的字典中加上transforms = [dict1,dict2,……]

示例:

aggregate:

transforms = [dict(
    type = 'aggregate',
    groups = [],        #用于分组的数组
    aggregations = [dict(
        target = 'y', func = 'sum', enabled = True),
    ]
  )]
"""
func参数可用:
"count","sum","avg","median","mode","rms","stddev","min","max","first","last"
"""复制代码

filter:

transforms = [dict(
    type = 'filter',
    target = 'y',
    operation = '>',
    value = 4
  )]
"""
operation参数可用:
"=","!=","<",">=",">","<=","[]","()","[)","(]","][",")(","](",")[","{}","}{"
"""复制代码

groupby:

transforms = [dict(
    type = 'groupby',
    groups = [],     #用于分组的数组
    styles = [
        dict(target = 'Moe', value = dict(marker = dict(color = 'blue'))),
        dict(target = 'Larry', value = dict(marker = dict(color = 'red'))),
        dict(target = 'Curly', value = dict(marker = dict(color = 'black')))
    ]
  )]复制代码

sort:

transforms = [dict(
    type = 'sort',
    target = 'x',     
    order = 'ascending'   #升序ascending,降序descending
  )]复制代码

注:(1) 使用transforms时,ptly.plot中要设置validate=False,go.Figure要改为dict,不然会报错

​ (2) target参数还可以设置为*marker.size*,*marker.color*等

相关资料

1.plot.ly/python/

2.github.com/plotly/plot…

ps:这只是一个小码农使用过程中的学习总结,参考了plotly官网和源码,如果有错误的地方欢迎指正哦~比心

你可能感兴趣的:(python)