一文爱上可视化神器plotly_express
目前使用和见识过最棒的可视化库。必须爱上它❤️
<!--MORE-->
注意:所有的图形在notebook中都是动态的
首先,我们看看官网上对plotly_express的定义:
Plotly Express is the easy-to-use, high-level interface to Plotly, which operates on "tidy" data and produces easy-to-style figures.
Every Plotly Express function returns a
graph_objects.Figure
object whosedata
andlayout
has been pre-populated according to the provided arguments.
Plotly Express
是一个新的高级 Python
可视化库:它是 Plotly.py
的高级封装,它为复杂的图表提供了一个简单的语法,内置了大量实用、现代的绘图模板,用户只需调用简单的API函数,即可快速生成漂亮的互动图表。
安装非常简单,使用pip命令即可
使用的时候,导入import之后一般是用px
别名
pip install plotly_express # 安装
import plotly_express as px # 导入
px中有几个内置数据,可以供用户使用
比如使用其中著名的iris
数据,见如下的使用方法:
gapminder = px.data.gapminder()
gapminder.head()
设置线条类型
# line 图
fig = px.line(gapminder,x="year",y="lifeExp",color="continent",line_group="continent",
hover_name="country",line_shape="spline",render_mode="svg")
fig.show()
# area 图
fig = px.area(gapminder,x="year",y="pop",color="continent",line_group="country")
fig.show()
散点图是最简单的图形,有两个属性即可作图。下面的color属性表示颜色根据哪个属性
gapminder2007 = gapminder.query("year==2007")
px.scatter(gapminder2007,x="gdpPercap",y="lifeExp")
注意各个参数的含义
改变每个点的大小-size
px.scatter(gapminder2007,x="gdpPercap",y="lifeExp"
,color="continent" # 区分颜色
,size="pop" # 区分圆的大小
,size_max=60)
px.scatter(gapminder2007
,x="gdpPercap"
,y="lifeExp"
,color="continent" # 区分颜色
,size="pop" # 区分圆的大小
,size_max=60
,hover_name="country"
,log_x=True)
px.scatter(gapminder # 绘图使用的数据
,x="gdpPercap" # 横纵坐标使用的数据
,y="lifeExp"
,color="continent" # 区分颜色的属性
,size="pop" # 区分圆的大小
,size_max=60 # 圆的最大值
,hover_name="country" # 图中可视化最上面的名字
,animation_frame="year" # 横轴滚动栏的属性year
,animation_group="country"
,facet_col="continent" # 按照国家country属性进行分格显示
,log_x=True
,range_x=[100,100000]
,range_y=[25,90]
,labels=dict(pop="Populations", # 属性名字的变化,更直观
gdpPercap="GDP per Capital",
lifeExp="Life Expectancy"))
fig = px.choropleth(gapminder,locations="iso_alpha",color="lifeExp",
hover_name="country",animation_frame="year",
range_color=[20,80],projection="natural earth")
fig.show()
fig = px.scatter_geo(gapminder,locations="iso_alpha",
color="continent",hover_name="country",
size="pop",animation_frame="year",
projection="natural earth")
fig.show()
去掉projection参数,看不同的效果
px.scatter_geo(gapminder,locations="iso_alpha",color="continent",hover_name="country",size="pop",animation_frame="year"
#,projection="natural earth" # 去掉projection参数
)
查看文档并导入数据
# 查看数据文档
print(px.data.iris.__doc__)
# 导入数据集
iris = px.data.iris()
iris
# 查看属性
iris["species"].value_counts()
# 如何知道每个点的种类:指定颜色参数color="species"
px.scatter(iris,x="sepal_width",y="sepal_length",color="species")
上方增加直方图,右方增加细条图
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",
marginal_x="histogram",marginal_y="rug" # 主要是这两个参数决定
)
px.scatter(iris,x="sepal_width",y="sepal_length",color="species"
,marginal_y="violin",marginal_x="box" # 定义两个属性
,trendline="ols" # 显示数据的变化趋势
)
这个图真的是非常棒,一条语句可以直接生成矩阵图
px.parallel_coordinates(iris,color="species_id",labels={"species_id":"Species",
"sepal_width":"Sepal Width",
"sepal_length":"Sepal Length",
"petal_length":"Petal Length",
"petal_width":"Petal Width"},
color_continuous_scale=px.colors.diverging.Tealrose,
color_continuous_midpoint=2)
在上下分别加上误差值
# 对当前值加上下两个误差值
iris["e"] = iris["sepal_width"] / 100
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",error_x="e",error_y="e")
px.density_contour(iris,x="sepal_width",y="sepal_length",color="species")
等密度线图加上其他的图
px.density_contour(iris,x="sepal_width",y="sepal_length",color="species",
marginal_x="rug",marginal_y="histogram" # 在密度图的基础上,指定另外两种图形
)
px.density_heatmap(iris,x="sepal_width",y="sepal_length",
marginal_y="rug",marginal_x="histogram" # 在密度图的基础上,指定另外两种图形
)
根据性别的不同进行分类作图
# 根据性别属性进行分类作图
fig = px.scatter(tips,x="total_bill",y="tip",color="size",render_mode="webgl",
facet_col="sex",color_continuous_scale=px.colors.sequential.Viridis)
fig.show()
fig = px.parallel_categories(tips,color="size",color_continuous_scale=px.colors.sequential.Inferno)
fig.show()
多重属性的柱状图
fig = px.bar(tips,x="sex",y="total_bill",color="smoker",barmode="group"
,facet_row="time",facet_col="day",category_orders={"day": ["Thur","Fri","Sat","Sun"],"time":["Lunch", "Dinner"]})
fig.show()
px.histogram(tips,x="sex",y="tip",histfunc="avg",color="smoker",barmode="group",
facet_row="time",facet_col="day",category_orders={"day":["Thur","Fri","Sat","Sun"],
"time":["Lunch","Dinner"]})
# notched=True显示连接处的锥形部分
px.box(tips,x="day",y="total_bill",color="smoker",notched=True)
如果不加notched
参数,则连接处则会是矩形,而不是锥形
px.violin(tips,x="smoker",y="tip",color="sex",box=True # box是显示内部的箱体
,points="all",hover_data=tips.columns # 结果中显示全部数据
)
使用的是election数据集
fig = px.scatter_3d(election,x="Joly",y="Coderre",z="Bergeron" # 指定3个轴
,color="winner",size="total",hover_name="district_id" # 指定颜色种类、大小和显示名称
,symbol="result" # 右边的圆形和菱形
,color_discrete_map={"Joly":"blue","Bergeron":"green","Coderre":"red"} # 改变默认颜色
)
fig.show()
px.line_3d(election,x="Joly",y="Coderre",z="Bergeron",color="winner",line_dash="winner")
使用的数据是wind
fig = px.scatter_polar(wind,r="frequency",theta="direction",color="strength",symbol="strength"
,color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()
fig = px.line_polar(wind,r="frequency",theta="direction",color="strength",line_close=True
,color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()
fig = px.bar_polar(wind,r="frequency",theta="direction",color="strength",template="plotly_dark"
,color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()
在px库中,px.colors模块中有很多可用的色标和序列:定性的、序列型的、离散的、循环等。
px.colors.qualitative.swatches()
px.colors.sequential.swatches() # 部分截图
主题允许用户控制图形范围的设置,包含边距、字体、背景颜色、刻度定位等。px内置的主题有3种:
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",marginal_x="box",
marginal_y="histogram",height=600,trendline="ols",template="plotly")
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",marginal_x="box",
marginal_y="histogram",height=600,trendline="ols",template="plotly_white")
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",marginal_x="box",
marginal_y="histogram",height=600,trendline="ols",template="plotly_dark")
以散点图为例,对绘制的参数进行解释
def scatter(data_frame, 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_frame=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', title=None,
template=None, width=None, height=None):
return
其他作图方法的作图参数类似
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。