Python

plotly-express-1-爱上可视化神器plotly_e

2020-07-05  本文已影响0人  皮皮大

一文爱上可视化神器plotly_express,目前使用和见识过最棒的可视化库。必须爱上它❤️

目录

image.png

\color{red}{Attention}:下面的所有图在jupyter notebook均是动态可交互式图形

\color{red}{Attention}:下面的所有图在jupyter notebook均是动态可交互式图形

\color{red}{Attention}:下面的所有图在jupyter notebook均是动态可交互式图形

什么是plotly_express

首先,我们看看官网上对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 whose data and layout 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中有几个内置数据,可以供用户使用

image

比如使用其中著名的iris数据,见如下的使用方法:

image

使用内置数据集Gapminder

如何使用内置数据集

选择数据
gapminder = px.data.gapminder()
gapminder.head()
image
查看属性
image

line图

设置线条类型

# 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()
image.png

堆积区域图area

# area 图
fig = px.area(gapminder,x="year",y="pop",color="continent",line_group="country")
fig.show()
image

散点图

散点图是最简单的图形,有两个属性即可作图。下面的color属性表示颜色根据哪个属性

gapminder2007 = gapminder.query("year==2007")
px.scatter(gapminder2007,x="gdpPercap",y="lifeExp")

注意各个参数的含义

image

改变每个点的大小-size

px.scatter(gapminder2007,x="gdpPercap",y="lifeExp"
           ,color="continent"  # 区分颜色
           ,size="pop"   # 区分圆的大小
           ,size_max=60)
image

悬停参数-hover_name

px.scatter(gapminder2007
           ,x="gdpPercap"
           ,y="lifeExp"
           ,color="continent"  # 区分颜色
           ,size="pop"   # 区分圆的大小
           ,size_max=60
           ,hover_name="country"
           ,log_x=True)
image

分块facet_col+滚动条animation_frame

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"))
image

地理图

choropleth-面分布图
fig = px.choropleth(gapminder,locations="iso_alpha",color="lifeExp",
             hover_name="country",animation_frame="year",
             range_color=[20,80],projection="natural earth")
fig.show()
image
scatter_geo地图_点分布
fig = px.scatter_geo(gapminder,locations="iso_alpha",
                     color="continent",hover_name="country",
                     size="pop",animation_frame="year",
                     projection="natural earth")

fig.show()
image

去掉projection参数,看不同的效果

px.scatter_geo(gapminder,locations="iso_alpha",color="continent",hover_name="country",size="pop",animation_frame="year"
#,projection="natural earth"   # 去掉projection参数
)
image
line_geo-线型地理图
image

使用内置数据集iris

查看文档并导入数据

# 查看数据文档
print(px.data.iris.__doc__)

# 导入数据集
iris = px.data.iris()
iris 

# 查看属性
iris["species"].value_counts()
image

绘制散点图

# 如何知道每个点的种类:指定颜色参数color="species"
px.scatter(iris,x="sepal_width",y="sepal_length",color="species")
image

联合分布图(散点图+直方图)

上方增加直方图,右方增加细条图

px.scatter(iris,x="sepal_width",y="sepal_length",color="species",
           marginal_x="histogram",marginal_y="rug"  # 主要是这两个参数决定
          )
image

violin-小提琴图

px.scatter(iris,x="sepal_width",y="sepal_length",color="species"
           ,marginal_y="violin",marginal_x="box"    # 定义两个属性
           ,trendline="ols"  # 显示数据的变化趋势
          )
image.png

SPLOM-散点矩阵图

这个图真的是非常棒,一条语句可以直接生成矩阵图

image

平行坐标图

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)
image

箱体误差图

在上下分别加上误差值

# 对当前值加上下两个误差值
iris["e"] = iris["sepal_width"] / 100
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",error_x="e",error_y="e")

image

等密度线图density_contour

px.density_contour(iris,x="sepal_width",y="sepal_length",color="species")

[站外图片上传中...(image-90cadd-1593914392458)]

等密度线图加上其他的图

px.density_contour(iris,x="sepal_width",y="sepal_length",color="species",
                  marginal_x="rug",marginal_y="histogram"   # 在密度图的基础上,指定另外两种图形
                  )

image

密度热力图density_heatmap

px.density_heatmap(iris,x="sepal_width",y="sepal_length",
                  marginal_y="rug",marginal_x="histogram"   # 在密度图的基础上,指定另外两种图形
                  )

image

小费tips实例

image

散点图

根据性别的不同进行分类作图

# 根据性别属性进行分类作图
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()

[站外图片上传中...(image-7c13a7-1593914392458)]

并行类别图

fig = px.parallel_categories(tips,color="size",color_continuous_scale=px.colors.sequential.Inferno)
fig.show()

[站外图片上传中...(image-153026-1593914392458)]

Bar-柱状图

image

多重属性的柱状图

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()

image

Histogram-直方图

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"]})

image

box-箱型图

# notched=True显示连接处的锥形部分
px.box(tips,x="day",y="total_bill",color="smoker",notched=True)

image

如果不加notched参数,则连接处则会是矩形,而不是锥形

image

violin-小提琴图

px.violin(tips,x="smoker",y="tip",color="sex",box=True   # box是显示内部的箱体
          ,points="all",hover_data=tips.columns  # 结果中显示全部数据
         )

image

3D图形绘制

使用的是election数据集

image

散点3D图

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()

image

line-3D图

px.line_3d(election,x="Joly",y="Coderre",z="Bergeron",color="winner",line_dash="winner")

image

)

极坐标图-内置数据wind

使用的数据是wind

image

scatter-polar散点极坐标

fig = px.scatter_polar(wind,r="frequency",theta="direction",color="strength",symbol="strength"
                      ,color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()

image

line_polar线性极坐标

fig = px.line_polar(wind,r="frequency",theta="direction",color="strength",line_close=True
                      ,color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()

image

bar_polar柱状极坐标

fig = px.bar_polar(wind,r="frequency",theta="direction",color="strength",template="plotly_dark"
                  ,color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()

image

颜色面板和序列

在px库中,px.colors模块中有很多可用的色标和序列:定性的、序列型的、离散的、循环等。

px.colors.qualitative.swatches()

image
px.colors.sequential.swatches()  # 部分截图

image image

主题

主题允许用户控制图形范围的设置,包含边距、字体、背景颜色、刻度定位等。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")

image
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",marginal_x="box",
          marginal_y="histogram",height=600,trendline="ols",template="plotly_white")

image
px.scatter(iris,x="sepal_width",y="sepal_length",color="species",marginal_x="box",
          marginal_y="histogram",height=600,trendline="ols",template="plotly_dark")

image

参数详解

以散点图为例,对绘制的参数进行解释

定义

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

参数解释

其他作图方法的作图参数类似

参考资料

可视化神器plotly_express详解

API详解

Plotly_express in python

上一篇 下一篇

猜你喜欢

热点阅读