目录
第一部分: plotly的交互 I. Zoom、Pan和Hover第二部分: cuff s画图 I. 库的安装与导入 II. 条形图 III. 直方图 IV. 折线图 V. 散点图 VI. 饼图 VII. 盒形图 VIII. 热力图(heatmap) IX. K线图(蜡烛图) X. iplot()通用型参数详解第三部分: plotly.express画图第四部分: 结合plotly I. cuff s / express + plotly画图 II. 为什么不单独用plotly画图? III. 图表导出 IV. 补充
plotly.py是一个用于python的交互式、基于浏览器的高级声明式绘图库,它拥有所有绘图库中最全的API和最强大的交互工具,支持科学、统计学、金融、地理、3D等多个领域多种样式的图表。 plotly.py建立在plotly.js之上,plotly.js则建立在d3.js和stack.gl之上,前者被广泛应用于印刷出版物和创建网站。
cuff s是一个plotly的"包装器", 官方的原话是"a library for easy interactive Pandas charting with Plotly". cuff s将所有的绘图方法都封装到了iplot()方法中(可以类比matplotlib中的plot()方法),通过它, 我们用仅仅一行代码就能画出简洁、美观(publication-quality)、多样(40+)的交互式图表.
plotly.express是另一个plotly的包装器,它的定位是"rapid data exploration and figure generation" 。express支持的图表类型相比cuff s要少一些,但更加具有针对性。另外, express还自带一些toy datasets,这一点与seaborn类似(事实上它也的确参考了seaborn)
总结一下,cuff s侧重于数据呈现,express侧重于数据探索,plotly则拥有最全的API。
那么该如何使用这三个库呢?
我的建议是:如果你只是希望把数据漂亮地呈现出来,就使用cuff s;而如果你是想要从数据中发现可能存在的隐藏规律,那就使用express;plotly则把它作为前面两个库的补丁,用来补全cuff s和express不方便实现的layout细节。
(cuff s和express需要结合pandas使用, 对pandas还不熟悉的同学可以参考我的另一个专栏: pandas handbook )
第一部分: plotly的交互I. Zoom、Pan和Hover
在cuff s和plotly生成的每张二维图表的右上角, 我们都可以看到下图红框框起的几个图标
相机图标用于将图表下载为png图片
Home图标用于重置坐标轴
zoom用于放大某个区域, 具体的做法是, 点击并按住鼠标左键移动选择目标区域, 然后释放鼠标。如果要返回原始视图, 在绘图区域的任意位置双击或点击Reset axes即可
zoom图标是默认选择的
pan用于平移图表区域, 先单击pan图标, 然后按住鼠标左键拖动就可以实现平移区域. 同样地, 在任意位置双击或点击Reset axes返回原始视图
而hover就是在鼠标悬停时显示数据的效果,具体有两种,即'Show closest data on hover'和'Compare data on hover'。'Show closest data on hover'和'zoom'一样是默认选择的, 且'Show closest data on hover'和'Compare data on hover'必须选择其中之一。
下面这个图标, 仅显示光标下最接近的数据点的数据
而如果选择下面这个图标,则会显示具有相同x值的所有数据点的数据
have a try直通车:https://plot.ly/~plotly2_demo/480.
这里仅介绍常用的几个功能, 剩余的留待读者自己探索, 下面开始介绍具体的图表.
第二部分: cuff s画图I. 库的安装与导入
安装
直接pip install cuff s, 关联的plotly库也会同时安装好(默认安装的是3.10.0版本的plotly)
导入
我们接下来介绍的绘图, 主要是对pandas对象调用iplot()方法, 一般只需导入cuff s
import cuff s as cf
II. 条形图
barmode : 条形图样式, 字符串
group(簇状)
stack(堆叠)
overlay(覆盖)
* Only valid when kind='bar'
orientation : 方向, 字符串, v为垂直, h为水平, 默认为v
* Only valid when kind is 'histogram','bar' or 'box'
下面是一些不怎么用得到的参数:
sortbars : bool
Sort bars in descending order
* Only valid when kind='bar'
bargap : float
Sets the gap between bars
[0,1)
* Only valid when kind is 'histogram' or 'bar'
bargroupgap : float
Set the gap between groups
[0,1)
* Only valid when kind is 'histogram' or 'bar'
原始数据:
Series条形图
默认主题: ggplot
white主题
polar主题
自定义配色
Data 条形图
簇状柱形图(默认)
colorscale一览:
堆积条形图:
覆盖条形图
III. 直方图
bins : 直方图形的数量, int or tuple
if int:
Specifies the number of bins
if tuple:
(start, end, size)
start : starting value
end: end value
size: bin size
* Only valid when kind='histogram'
orientation : 方向, 字符串, v为垂直, h为水平, 默认为v
* Only valid when kind is 'histogram','bar' or 'box'
bargap : 设置bar之间的距离, float型, 值在[0,1)之间
* Only valid when kind is 'histogram' or 'bar'
bargroupgap : 设置bargroup之间的距离, float型, 值在[0,1)之间,
对直方图而言bargap和bargroupgap参数功能一样, 两个参数都用不到
* Only valid when kind is 'histogram' or 'bar'
histnorm : 把histgram trace 归一化, string
percent
probability
density
probability density
1. Sets the type of normalization for an histogram trace.
By default the height of each bar displays the frequency
of occurrence, i.e., the number of times this value was
found in the corresponding bin.
2. If set to 'percent', the height of each bar
displays the percentage of total occurrences found within
the corresponding bin.
3. If set to 'probability', the height of each b
displays the probability that an event will fall into the
corresponding bin.
4. If set to 'density', the height of each bar is
equal to the number of occurrences in a bin divided by the
size of the bin interval such that summing the area of all
bins will yield the total number of occurrences.
5. If set to 'probability density',
the height of each bar is equal to the number of probability
that an event will fall into the corresponding bin divided
by the size of the bin interval such that summing the area
of all bins will yield 1.
* Only valid when kind='histogram'
原始数据:
多列的直方图:
只选数值列,且列之间数值不应相差过大
设置subplots:
单列的直方图:
换一下朝向
设置规格化:
IV. 折线图
symbol : dict, list or string
string : applies to all traces
list : applies to each trace in the order specified
dict: {column:value} for each column in the data
The symbol that is drawn on the plot for each marker, 默认为'circle'
Valid only when mode includes markers
circle
circle-dot
diamond
square
and many more...
(see plotly.validators.scatter.marker.SymbolValidator.values)
size : string or int
Size of marker, 默认为12
Valid only if marker in mode
原始数据:
设置symbol:
设置symbol的size:
设置text:
试一下secondary_y:
画一个股价变化图:
设置subplots
设置fill效果, 同时共享x轴
最后, 我们还可以在图上添加标识线, 方便我们看到指定区间内的变化, 指定vline添加竖线, 指定hline添加横线, 指定vspan添加纵向的阴影区域, 添加hspan添加横向的阴影区域
添加一条标识线
2007-02-13金融危机开始时间
指定时间区间
添加纵向的阴影区域
也可以为vspan指定字典, 这样可以指定阴影区域的颜色和不透明度
hline、hspan同理, 不再赘述
V. 散点图
原始数据:
小费数据集
VI. 饼图
labels : string
Name of the column that contains the labels.
* Only valid when kind='pie'
values : string
Name of the column that contains the values.
* Only valid when kind='pie'
textinfo : string
Sets the information to be displayed on
the legends
label
percent
value
* or ony combination of the above using
'+' between each item
ie 'label+percent'
下面这些参数不怎么用得到
sort : bool
If True it sorts the labels by value
pull : float [0-1]
Pulls the slices from the centre
hole : float [0-1]
Sets the size of the inner hole
linecolor : string
Sets the color for the contour line of the slices
linewidth : string
Sets the width for the contour line of the slices
textcolor : string
Sets the color for the text in the slices
textposition : string
Sets the position of the legends for each slice
outside
inner
原始数据:
设置一下textinfo:
VII. 盒形图
原始数据:
依然是小费数据集
可以很明显地看到周四、周六有异常值
VIII. 热力图(heatmap)
IX. K线图(蜡烛图)
X. iplot()通用型参数详解
iplot(kind='scatter', data=None, layout=None, filename='', sharing=None,
='', x ='', y ='', z ='', theme=None, colors=None,
colorscale=None, fill=False, width=None, dash='solid', mode='lines',
interpolation='linear', symbol='circle', size=12, barmode='',
sortbars=False, bargap=None, bargroupgap=None, bins=None, histnorm='',
histfunc='count', orientation='v', boxpoints=False, annotations=None,
keys=False, bestfit=False, bestfit_colors=None, mean=False, mean_colors=None,
categories='', x='', y='', z='', text='', gridcolor=None, zerolinecolor=None,
margin=None, labels=None, values=None, secondary_y='', secondary_y_ ='',
subplots=False, shape=None, error_x=None, error_y=None, error_type='data',
locations=None, lon=None, lat=None, as =False, asDates=False,
asFigure=False, asImage=False, dimensions=None, asPlot=False, asUrl=False,
online=None, **kwargs)
通用参数
kind 图表类型, 默认为scatter, 可以选择 scatter, bar, box, spread, ratio
heatmap, surface, histogram, bubble, bubble3d, scatter3d
scattergeo, ohlc, candle, pie, choroplet
mode : dict, list or string, 默认为'lines'
1. string : applies to all traces
2. list : applies to each trace in the order specified
3. dict: {column:value} for each column in the data
Plotting mode for scatter trace
lines
markers
lines+markers
lines+text
markers+text
lines+markers+text
什么是trace ?
"A trace is just the name we give a collection of data and the
specifications of which we want that data plotted. Notice that
a trace will also be an itself, and these will be named
according to how you want the data displayed on the plotting surface."
theme 布局主题, ['ggplot', 'pearl', 'solar', 'space', 'white',
'polar', 'henanigans']中选一
图表标题
x : 包含x轴数值的列名, 字符串
y : 包含y轴数值的列名, 字符串
z : 包含z轴数值的列名, 字符串
x x轴坐标轴标签
y y轴坐标轴标签
z z轴坐标轴标签
colors : dict, list or string
{key:color} to specify the color for each column
[colors] to use the colors in the defined order
colorscale : string, Color scale name
If the color name is preceded by a minus (-) , then
the scale is inversed
Only valid if 'colors' is null
See cuff s.colors.scales() for available scales
text : 包含文本值的列名, 字符串
dash : dict, list or string
1. string : applies to all traces
2. list : applies to each trace in the order specified
3. dict: {column:value} for each column in the data
Drawing style of lines
solid
dash
dashdot
dot
secondary_y : 在右边y轴上绘制的列的列名, 字符串或列表(可以为多个)
secondary_y_ : secondary_y轴标签
subplots : If true then each trace is placed in subplot layout. bool型,
True or False
shape : subplots的具体布局, 值为行数和列数组成的元组, (rows,cols),
如果省略会自动设置 * Only valid when subplots=True
asFigure : bool
If True returns plotly Figure
第三部分: plotly.express画图
前面提到两个包装器的定位是不一样的,express的API侧重于数据探索,cuff s则更全面.
异同具体体现在:
- express支持的图表类型相比cuff s少很多,只有二十几种,因为侧重于data exploration,所以饼图、蜡烛图等图表也不被支持;而cuff s则支持40多种图表,覆盖更全面。但两者也有重叠,比如常见的散点图就可以用两个包装器分别实现。
- express中一个方法对应一个图表,如px.scatter()、px.scatter_matrix()等;而cuff s则是通过iplot()方法中的kind参数指定不同类型的图表。这有点像是matplotlib中单种图表的方法和plot()方法的区别。我个人还是更喜欢cuff s的封装方式
- 相同的一点是express和cuff s都是与pandas结合使用的,express把Data 作为所有画图方法的第一个参数(只能是Data , 传入Series会报错),而cuff s则是对pandas对象调用iplot()方法
- express自带toy datasets,它通过如px.data.tips()、px.data.iris()的形式加载本地数据集,返回的是一个Data 对象。这一点跟seaborn类似。(toy datasets的完整名单为:tips、iris、gapminder、wind、election、carshare)
- 既然是针对数据探索的,express还是有一些独到的地方, 比如地理数据的可视化就让人印象很深刻(scatter_mapbox)
I. 安装与导入
plotly.express以前通过plotly_express包单独安装,但现在是plotly的一部分,通常的引入约定为:
import plotly.express as px
II. scatter
原始数据用cuff s画是这样的:
用px则是这样的:
返回的是一个Figure对象
比较不一样的是px还可以画出seaborn风格的图:
另外px.scatter()对气泡图的支持更好:
housing数据集
matplotlib版本的气泡图
express版本的气泡图:
better
详细的colorscale见下方链接:
Plotly Express直通车
https:// .zhihu.com/?target=https%3A//plot.ly/python/plotly- express/%23builtin-color-scales-and-sequences-and-a-way-to-see-them
scatter(data_ , x=None, y=None, color=None, symbol=None, size=None,
hover_name=None, hover_data=None, text=None, facet_row=None,
facet_col=None, error_x=None, error_x_minus=None, error_y=None,
error_y_minus=None, animation_ =None, animation_group=None,
category_orders={}, labels={}, color_discrete_sequence=None,
color_discrete_map={}, color_continuous_scale=None, range_color=None,
color_continuous_midpoint=None, symbol_sequence=None, symbol_map={},
opacity=None, size_max=None, marginal_x=None, marginal_y=None,
trendline=None, trendline_color_override=None, log_x=False,
log_y=False, range_x=None, range_y=None, render_mode='auto',
=None, template=None, width=None, height=None)
data_ A 'tidy' pandas.Data
x Data 中的列名字符串, 数据点的x轴坐标
y Data 中的列名字符串, 数据点的y轴坐标
图表标题
template 图表主题, 字符串, ['ggplot2', 'seaborn', 'plotly', 'plotly_white',
'plotly_dark', 'presentation', 'xgridoff', 'none']其中的一个
size Data 中的列名字符串, 把该列的值与数据点的大小相关联
color Data 中的列名字符串, 把该列的值与颜色相关联
marginal_x 字符串, ('rug', 'box', 'violin', 'histogram')的其中之一;
如果设置, 则在主题上方绘制一个水平子图, 以显示x的分布
marginal_y 字符串, ('rug', 'box', 'violin', 'histogram')的其中之一;
如果设置, 则在主题右侧绘制一个垂直子图, 以显示y的分布
color_continuous_scale 有效的CSS颜色字符串列表, 当color指代的列包含数值型数据时,
此列表用于构建连续的color scale, 可以从
plotly_express.colors.sequential,
plotly_express.colors.diverging 和
plotly_express.colors.cyclical中选择
width 以像素为单位的图像宽度, 整数, 默认为None
height 以像素为单位的图像高度, 整数, 默认为600
III. scatter_mapbox()
当x和y是经纬度时, 我们应该选择scatter_mapbox(),把数据点投射在地图上
再来一张我们中国的:
scatter_mapbox(data_ , lat=None, lon=None, color=None, text=None,
hover_name=None, hover_data=None, size=None,
animation_ =None, animation_group=None,
category_orders={}, labels={}, color_discrete_sequence=None,
color_discrete_map={}, color_continuous_scale=None,
range_color=None, color_continuous_midpoint=None,
opacity=None, size_max=None, zoom=8, =None,
template=None, width=None, height=None)
data_ A 'tidy' pandas.Data
lon Data 中的列名字符串, 数据点的经度
lat Data 中的列名字符串, 数据点的纬度
size Data 中的列名字符串, 把该列的值与数据点的大小相关联
color Data 中的列名字符串, 把该列的值与颜色相关联
图表标题
text Data 中的列名字符串, 该列的值在图中显示为文本标签(text labels)
(静态文本标签)
hover_name Data 中的列名字符串, 该列的值在悬停提示框的顶部以粗体显示
hover_data Data 中的列名字符串的列表, 这些列的值在悬停提示框中作为额外的
数据显示
color_continuous_scale 有效的CSS颜色字符串列表, 当color指代的列包含数值型数据时,
此列表用于构建连续的color scale, 可以从
plotly_express.colors.sequential,
plotly_express.colors.diverging 和
plotly_express.colors.cyclical中选择
size_max 使用'size'关键字时数据点的最大尺寸, 整数, 默认为20
zoom 地图缩放的级别, 0-20之间的整数, 默认为8
IV. scatter_matrix()
原始数据集如下
scatter_matrix()默认选择所有列
接下来只选择数值列
scatter_matrix(data_ , dimensions=None, color=None, symbol=None, size=None,
hover_name=None, hover_data=None, category_orders={}, labels={},
color_discrete_sequence=None, color_discrete_map={},
color_continuous_scale=None, range_color=None,
color_continuous_midpoint=None, symbol_sequence=None,
symbol_map={}, opacity=None, size_max=None, =None,
template=None, width=None, height=None)
data_ A 'tidy' pandas.Data
图表标题
template 图表主题, 字符串, ['ggplot2', 'seaborn', 'plotly', 'plotly_white',
'plotly_dark', 'presentation', 'xgridoff', 'none']其中的一个
第四部分: 结合plotly
plotly的主要模块是 plotly.graph_ s ,它包含生成图表对象的函数,导入方式为
import plotly.graph_ s as go
在plotly中定义一个图表需要用到三个对象: Data, Layout和Figure, 它们的含义如下:
Data 包含要绘制的所有数据 Layout 定义图表外观, 绘制与数据无关的features(如标题, 轴标签, 注释, 字体) Figure figure对象是最后要绘制的对象, 是一个包含data对象和layout对象的类字典对象
go.Figure()用于初始化一个figure对象, 参数细节如下:
Figure(data=None, layout=None, s=None, skip_invalid=False, **kwargs)
data 'data'属性是一个trace实例的元组, 可以被指定为:
- trace实例的列表或元组, 如[Scatter(...), Bar(...)]
- 单个trace实例, 如Scatter(...), Bar(...), etc.
- 字符串/值键值对字典的列表或元组, 键一般有x, y和type, 其余的取决于你所画的图表,
'type'属性指定trace类型(即图表类型), 剩余的键值对被传递给指定trace类型的构造器
'type'是以下类型之一:
['area', 'bar', 'barpolar', 'box','candlestick', 'carpet', 'choropleth',
'choroplethmapbox', 'cone', 'contour', 'contourcarpet', 'densitymapbox',
'funnel', 'funnelarea', 'heatmap', 'heatmapgl', 'histogram',
'histogram2d', 'histogram2dcontour', 'indicator','isosurface', 'mesh3d',
'ohlc', 'parcats', 'parcoords', 'pie', 'pointcloud', 'sankey','scatter',
'scatter3d', 'scattercarpet', 'scattergeo', 'scattergl', 'scattermapbox',
'scatterpolar', 'scatterpolargl','scatterternary', 'splom', 'streamtube',
'sunburst', 'surface', 'table', 'violin','volume', 'waterfall']
layout 'layout'属性是一个Layout实例, 可以指定为:
- 一个plotly.graph_objs.Layout实例
- 一个字符串/值键值对的字典(会被传递给Layout构造器)
常用属性有:
: 标题
plotly.graph_ s.layout. 实例或具有兼容属性的字典,
如"layout": {" ": {"text": "A Bar Chart"}}或
"layout": {" ": dict(text="A Bar Chart")}
详细的属性可以通过help(plotly.graph_ s.layout. )查看, 下同
annotations: 注释
plotly.graph_ s.layout.Annotation实例或具有兼容属性的字典的元组
I. cuff s / express + plotly画图
还记得吗, pandas对象的iplot方法中有一个asFigure参数, 默认为False, 如果设置为True则返回一个plotly的Figure对象(express中的画图方法直接返回figure对象)。对Data 和Series而言, 相当于自带Data, 所以在需要添加一些iplot()方法或express的方法中没有或不健全的feature时(比如箭头注释), 我们就可以使用这些Figure对象。
举个添加箭头注释的例子:
原始数据画K线图
将asFigure设为True, 对返回的Figure对象调用update_layout方法, 传入一个Annotation实例的列表
也可以对参数annotations传入一个关键字/值的字典的列表, 这些字典会被传给Annotation的构造器, 最终转化为Annotation对象
如果觉得键/值的字典形式不直观, 还可以选择下面这种dict()构造字典的方式
go.layout.Annotation()方法的API如下
Annotation(arg=None, align=None, arrowcolor=None, arrowhead=None, arrowside=None,
arrowsize=None, arrowwidth=None, ax=None, axref=None, ay=None,
ayref=None, bgcolor=None, bordercolor=None, borderpad=None,
borderwidth=None, captureevents=None, clicktoshow=None, font=None,
height=None, hoverlabel=None, hovertext=None, name=None, opacity=None,
showarrow=None, standoff=None, startarrowhead=None, startarrowsize=None,
startstandoff=None, templateitemname=None, text=None, textangle=None,
valign=None, visible=None, width=None, x=None, xanchor=None, xclick=None,
xref=None, xshift=None, y=None, yanchor=None, yclick=None, yref=None,
yshift=None, **kwargs)
x 箭头(尖)的x位置
y 箭头(尖)的y位置
text 注释的文本
plotly使用一部分HTML tag来做换行,字体格式变换之类的工作, 如
换行(<br>)
加粗(<b></b>)
斜体(<i></i>)
超链接(<a href='...'></a>), 其他支持的还有<em>、<sup>、<sub>、<span>
ax 设置箭头尾部(线)相对于头部(尖)的x位置
一个正的ax值表示箭头从右指向左, 负数则表示从左指向右
如果'axref'等于'pixel', 则ax单位是像素;
如果'axref'等于'x', 则ax就是对应坐标轴的绝对值
ay 设置箭头尾部(线)相对于头部(尖)的的y位置
一个正的ax值表示箭头从下指向上, 负数则表示从上指向下
如果'axref'等于'pixel', 则ax单位是像素;
如果'axref'等于'y'或'y2', 则ax就是对应坐标轴的绝对值
xref 设置注释的x坐标轴, 默认为'x'
如果设置为'x', 则参数'x'代表x坐标;
如果设置为'paper', 则参数'x'代表从画图区域左侧到注释的距离(0到1之间)
yref 设置注释的y坐标轴, 默认为'y2'
如果设置为'y'或'y2', 则参数'y'代表y坐标;
如果设置为'paper', 则参数'y'代表从画图区域底部到注释的距离(0到1之间)
showarrow 是否使用箭头式注释, 默认为True
如果为True, 则'text'被放置在箭头尾部附近
如果为False, 则'text'与提供的'x'和'y'对齐
arrowhead 选择箭头头部(尖)的样式
区间[0,8]之间的整数
font 设置注释文本的字体
The 'font' property is an instance of Font that may be specified as:
- An instance of plotly.graph_objs.layout.annotation.Font
- A dict of string/value properties that will be passed
to the Font constructor
具体的属性有:
color
family HTML font family, 包括 "Arial",
"Balto", "Courier New", "Droid Sans",, "Droid
Serif", "Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
size
上面讲了箭头注释,再举个设置标题的例子:
原始图表如下, 要将标题设置为居中, 同时调大字号,
这样子做:
go.layout.
(arg=None, font=None, pad=None, text=None, x=None, xanchor=None, xref=None,
y=None, yanchor=None, yref=None, **kwargs)
text 设置图表标题
font 设置标题字体, plotly.graph_objs.layout. .Font实例或对应的字典
x 在从0(左)到1(右)的归一化坐标中, 设置相对于'xref'的x位置
xref 设置x参考的container, 默认为'container'
'container'指横跨整个图表区域的宽度
'paper'仅指画图区域的宽度
go.layout. .Font
Font(arg=None, color=None, family=None, size=None, **kwargs) size 设置字体大小
II. 为什么不单独用plotly画图?
plotly画图的好处是API非常全,真的非常全… 光marker的参数就有24个… 对应地,缺点就是作图的代码非常冗长。
举个例子, 假设你不懂pandas, 怎样只用plotly画出《 【S01E01】Matplotlib绘图与可视化 》开头的那张图
就是这张图plotly散点图的API如下:
go.Scatter(arg=None, cliponaxis=None, connectgaps=None, customdata=None,
customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None,
fill=None, fillcolor=None, groupnorm=None, hoverinfo=None,
hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None,
hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None,
idssrc=None, legendgroup=None, line=None, marker=None, =None,
src=None, mode=None, name=None, opacity=None, orientation=None,
r=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None,
stackgaps=None, stackgroup=None, stream=None, t=None, text=None,
textfont=None, textposition=None, textpositionsrc=None, textsrc=None,
tsrc=None, uid=None, uirevision=None, unselected=None, visible=None,
x=None, x0=None, xaxis=None, xcalendar=None, xsrc=None,
y=None, y0=None, yaxis=None, ycalendar=None, ysrc=None, **kwargs)
常用参数
x 设置x坐标
y 设置y坐标
name 设置trace名
trace name会作为图例的item出现以及鼠标在数据点上悬停时显示
用plotly是这样画的:
用plotly调整各种样式相当麻烦,而用cuff s是这样画的
所以我把plotly定位为cuff s的补充
III. 图表导出
i) 导出为html
前面生成的图表都是互交式的, 我们希望拿到这个图表的其他人见到的也是这个效果, 所以我们一般都是把它们保存为.html格式
方法一:网站导出
具体来说, 图表生成后, 先点击右下角的【Export to http:// ploy.ly 】(需要账号)
再次点击save
设置图表文件名, 再次点击保存
依次点击【Export】、【 HTML】、【Download As Html File】
下载的html文件效果如图所示:
方法二:plotly.io.write_html(fig, file='xxx.html')
结合之前的例子给一段完整的代码
最后一行的py指的是 import plotly as py 而不是 import plotly.plotly as py, 而config={'scrollZoom': True}是指下载的html可以使用滚动缩放.
plotly.io.write_html()方法一般来说指定保存路径就够了, 如果有额外的需求请键入help(py.io.write_html)查看, config配置可以看 这里
ii)导出为png/jpg/webp/svg/pdf/eps
plotly.io.write_image(fig, file='xxx.png/jpg/webp/svg/pdf/eps')
write_image(fig, file, format=None, scale=None, width=None, height=None, validate=True)
fig Figure对象
file 本地文件路径
scale 导出图表时使用的比例系数. 比例系数大于1.0会增加图像的分辨率(相对于图表的像素尺寸),
而小于1.0的比例系数会降低图像的分辨率
width 导出图像的宽度, 以像素为单位
height 导出图像的高度, 以像素为单位
IV. 补充
i)plotly版本问题
目前版本的cuff s(0.16)默认安装的是3.10.0版本的plotly, 而最新版本是4.1.1… 之所以会这样是因为0.16的cuff s只支持3.0.0以上, 4.0.0以下版本的plotly, 但有时我们需要用到plotly更高版本中才有的功能
在cuff s更新之前有一个权宜之计, 具体的操作过程如下
先更新plotly
pip install --upgrade plotly
再安装chart_studio
pip install chart-studio
然后找到cuff s的config files, 如下:
再把上面红框中的文件中的plotly.plotly改成chart_studio.plotly即可
另外,4之前的早期版本包含以“online”和“offline”模式创建图表的功能。在在线模式下, 图表被上传到Chart Studio云服务上, 而在离线模式下, 图表在本地渲染。4版本的plotly则只有离线模式,在线功能已经从plotly包中删除, 移动到新的chart-studio包中了.
在线功能的导入语句也从
from plotly.plotly import plot, iplot
变成了
from chart_studio.plotly import plot, iplot
要了解plotly版本四的新特性,可以参考 https:// plot.ly/python/v4-migra tion/
ii) 图表空白问题
如果是在Jupyter Notebook中遇到图表空白的情况, 只需要在命令行中运行
pip install jupyterlab==1.0 "ipywidgets==7.5"
或
conda install jupyterlab=1.0 "ipywidgets=7.5"
然后再重启一下即可
而如果是在Jupyter Lab中遇到这种情况, 需要安装对应的JupyterLab 插件. 具体的安装方法见 https://github.com/plotly/plotly.py#jupyterlab-support-python-35
如果安装过程中提示电脑上没有node.js, 可以在
https:// .zhihu.com/?target=http%3A//nodejs.org/zh-cn/download/package- manager/%23windows
下载对应版本的node.js. 友情提示,最后一步选'add to path'比较省事.
iii)不同的主题
plotly的版本4引入了新的渲染器框架,默认主题也变成了'plotly主题'.
版本4默认的'plotly'主题:
可用的主题有:
express使用的也是这些主题
而我们熟悉的cuff 使用的默认主题是这样的(cuff s有一个完全独立的主题系统,既不是版本三也不是版本四):
继续阅读与本文标签相同的文章
-
丰巢回应用照片刷脸取件:已第一时间下线
2026-05-15栏目: 教程
-
微博官方回应机构大V刷单:已暂停账号商业接单
2026-05-15栏目: 教程
-
综合布线各系统清单计算
2026-05-15栏目: 教程
-
一行代码解决忘记密码问题 教你用CMD命令查看所有连接过的WIFI密码
2026-05-15栏目: 教程
-
年度最具看点黑客大赛GeekPwn2019即将开战,顶级黑
2026-05-15栏目: 教程
