数据分析作图神器---plotly_express

Plotly Express 入门之路

Plotly Express 是一个新的高级 Python 可视化库:它是 Plotly.py 的高级封装,它为复杂的图表提供了一个简单的语法。 

受 Seaborn 和 ggplot2 的启发,它专门设计为具有简洁,一致且易于学习的 API :只需一次导入,您就可以在一个函数调用中创建丰富的交互式绘图,包括分面绘图(faceting)、地图、动画和趋势线。 它带有数据集、颜色面板和主题,就像 Plotly.py 一样。

Plotly Express 完全免费:凭借其宽松的开源 MIT 许可证,您可以随意使用它(是的,甚至在商业产品中!)。 

最重要的是,Plotly Express 与 Plotly 生态系统的其他部分完全兼容:在您的 Dash 应用程序中使用它,使用 Orca 将您的数据导出为几乎任何文件格式,或使用JupyterLab 图表编辑器在 GUI 中编辑它们!

用 pip install plotly_express 命令可以安装 Plotly Express。

使用 Plotly Express 轻松地进行数据可视化

一旦导入Plotly Express(通常是 px ),大多数绘图只需要一个函数调用,接受一个整洁的Pandas dataframe,并简单描述你想要制作的图。 如果你想要一个基本的散点图,它只是 px.scatter(data,x =“column_name”,y =“column_name”)

以下是 内置的 Gapminder 数据集 的示例,显示2007年按国家/地区的人均预期寿命和人均GDP 之间的趋势:

import plotly_express as px
gapminder = px.data.gapminder()
gapmindeer2007 = gapminder.query('year == 2007')
px.scatter(gapmindeer2007, x='gdpPercap', y='lifeExp')

如果你想通过大陆区分它们,你可以使用 color 参数为你的点着色,由 px 负责设置默认颜色,设置图例等:

px.scatter(gapmindeer2007, x='gdpPercap', y='lifeExp', color='continent')

这里的每一点都是一个国家,所以也许我们想要按国家人口来衡量这些点...... 没问题:这里也有一个参数来设置,它被称为 size

px.scatter(gapmindeer2007, x= 'gdpPercap', y='lifeExp', color='continent', size='pop', size_max=60)

如果你好奇哪个国家对应哪个点? 可以添加一个 hover_name ,您可以轻松识别任何一点:只需将鼠标放在您感兴趣的点上即可! 事实上,即使没有 hover_name ,整个图表也是互动的:

# 添加 facet_col 参数
px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          facet_col='continent')

 

也可以通过 facet_col =”continent“ 来轻松划分各大洲,就像着色点一样容易,并且让我们使用 x轴 对数(log_x)以便在我们在图表中看的更清晰:

# 添加 facet_col 参数
px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          facet_col='continent')

# 添加 facet_col 参数 和 log_x 参数
px.scatter(gapminder2007, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          facet_col='continent', log_x=True)

 

也许你不仅仅对 2007年 感兴趣,而且你想看看这张图表是如何随着时间的推移而演变的。 可以通过设置 animation_frame=“year” (以及 animation_group =“country” 来标识哪些圆与控制条中的年份匹配)来设置动画。 

在这个最终版本中,让我们在这里调整一些显示,因为像“gdpPercap” 这样的文本有点难看,即使它是我们的数据框列的名称。 我们可以提供更漂亮的“标签” (labels),可以在整个图表、图例、标题轴和悬停(hovers)中应用。 我们还可以手动设置边界,以便动画在整个过程中看起来更棒:

px.scatter(gapminder, x='gdpPercap', y='lifeExp', 
           color='continent', size='pop', 
           size_max=60, hover_name='country',
          animation_frame='year', animation_group='country',
          log_x=True, range_x=[10,100000],
          range_y=[25,90], labels=dict(pop='Population', gdpPercap='GDP per Capita', lifeExp='Life Expectancy'))

因为这是地理数据,我们也可以将其表示为动画地图,因此这清楚地表明 Plotly Express 不仅仅可以绘制散点图(不过这个数据集缺少前苏联的数据)。

px.choropleth(gapminder, locations='iso_alpha', color='lifeExp',
             hover_name='country', animation_frame='year',
             color_continuous_scale=px.colors.sequential.Plasma,
             projection='natural earth')

事实上,Plotly Express 支持三维散点图、三维线形图、极座标和地图上三元座标以及二维座标。 条形图(Bar)有二维笛卡尔和极座标风格。

进行可视化时,您可以使用单变量设置中的直方图(histograms)和箱形图(box)或小提琴图(violin plots),或双变量分布的密度等高线图(density contours)。 大多数二维笛卡尔图接受连续或分类数据,并自动处理日期/时间数据。 可以查看我们的图库 (ref-3) 来了解每个图表的例子。

 

iris = px.data.iris()
px.scatter(iris, x='sepal_width', y='sepal_length', 
           color='species', marginal_y='histogram',
          marginal_x='box', trendline='ols')

 

tips = px.data.tips()

px.scatter(tips, x='total_bill', y='tip',facet_row='time',
          facet_col='day',color='smoker',trendline='ols',
          category_orders={'day':['Thur', 'Fri', 'Sat', 'Sun'], 'time':['Lunch', 'Dinner']})

px.parallel_coordinates(iris, color='species_id',
                       color_continuous_scale=px.colors.diverging.Tealrose,
                       color_continuous_midpoint=2)

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

 

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

 

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

px.histogram(tips, x="total_bill", color="smoker", facet_row="day", facet_col="time")

px.box(tips, y="tip", x="sex", color="smoker", facet_col="day", facet_row="time", 
       category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]})

px.violin(tips, y="tip", x="sex", color="smoker", facet_col="day", facet_row="time",
         category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]})

election = px.data.election()

px.scatter_ternary(election, a="Joly", b="Coderre", c="Bergeron", color="winner", size="total", hover_name="district",
                   symbol="result", 
                   size_max=15, color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"}

 

px.scatter_3d(election, x="Joly", y="Coderre", z="Bergeron", color="winner", size="total", hover_name="district",
                  symbol="result", color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"})

 

wind = px.data.wind()

px.line_polar(wind, r="value", theta="direction", color="strength", line_close=True,
            color_discrete_sequence=px.colors.sequential.Plotly[-2::-1])

 

px.scatter_matrix(iris, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species")

# 平行座标的显示 跟原文一样,暂时不知道是哪个地方的差异 (备注:Python数据之道)
px.parallel_coordinates(iris, color='species_id', color_continuous_scale=['red','green', 'blue'])

用plotly调整

import plotly_express as px

fig = px.scatter(px.data.iris(), x='sepal_width', y='sepal_length', color='species')

import plotly.graph_objs as go

fig.update(layout=dict(legend=dict(orientation='h',y=1.1,x=0.5),
                      annotations=[go.layout.Annotation(text='this one is interesting', x=3.6, y=7.2)]))

 

px.bar_polar(wind, r="value", theta="direction", color="strength", template="plotly_dark",
            color_discrete_sequence= px.colors.sequential.Plotly[-2::-1])

 

以上就是plotly_express 的应用示例,主要内容参考:这里

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章