Plotly Express是对 Plotly.py 的高级封装,内置了大量实用、现代的绘图模板,用户只需调用简单的API函数,即可快速生成漂亮的互动图表,可满足90%以上的应用场景。

本文借助Plotly Express提供的几个样例库进行散点图、折线图、饼图、柱状图、气泡图、桑基图、玫瑰环图、堆积图、二维面积图、甘特图等基本图形的实现。

代码示例

import plotly.express as px
df = px.data.iris()
#Index(['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species','species_id'],dtype='object')
#      sepal_length  sepal_width  ...    species  species_id
# 0             5.1          3.5  ...     setosa           1
# 1             4.9          3.0  ...     setosa           1
# 2             4.7          3.2  ...     setosa           1
# ..            ...          ...  ...        ...         ...
# 149           5.9          3.0  ...  virginica           3
# plotly.express.scatter(data_frame=None, x=None, y=None,
# color=None, symbol=None, size=None,
# hover_name=None, hover_data=None, custom_data=None, text=None,
# facet_row=None, facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None,
# error_x=None, error_x_minus=None, error_y=None, error_y_minus=None,
# animation_frame=None, animation_group=None,
# category_orders=None, labels=None, orientation=None,
# color_discrete_sequence=None, color_discrete_map=None, color_continuous_scale=None,
# range_color=None, color_continuous_midpoint=None,
# symbol_sequence=None, symbol_map=None, 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)
# 以sepal_width,sepal_length制作标准散点图
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.show()#以鸢尾花类型-species作为不同颜色区分标志 color
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()#追加petal_length作为散点大小,变位气泡图 size
fig = px.scatter(df, x="sepal_width", y="sepal_length",color="species",size='petal_length')
fig.show()#追加petal_width作为额外列,在悬停工具提示中显示为额外数据 hover_data
fig = px.scatter(df, x="sepal_width", y="sepal_length",color="species", size='petal_length',hover_data=['petal_width'])
fig.show()#以鸢尾花类型-species区分散点的形状 symbol
fig = px.scatter(df, x="sepal_width", y="sepal_length",symbol="species" ,color="species", size='petal_length',hover_data=['petal_width'])
fig.show()#追加petal_width作为额外列,在悬停工具提示中以粗体显示。 hover_name
fig = px.scatter(df, x="sepal_width", y="sepal_length",symbol="species" ,color="species", size='petal_length',hover_data=['petal_width'], hover_name="species")
fig.show()#以鸢尾花类型编码-species_id作为散点的文本值 text
fig = px.scatter(df, x="sepal_width", y="sepal_length",symbol="species" ,color="species", size='petal_length',hover_data=['petal_width'], hover_name="species",text="species_id")
fig.show()#追加图表标题 title
fig = px.scatter(df, x="sepal_width", y="sepal_length",symbol="species" ,color="species", size='petal_length',hover_data=['petal_width'], hover_name="species",text="species_id",title="鸢尾花分类展示")
fig.show()#以鸢尾花类型-species作为动画播放模式 animation_frame
fig = px.scatter(df, x="sepal_width", y="sepal_length",symbol="species" ,color="species", size='petal_length',hover_data=['petal_width'], hover_name="species",text="species_id",title="鸢尾花分类展示",animation_frame="species")
fig.show()#固定X、Y最大值最小值范围range_x,range_y,防止动画播放时超出数值显示
fig = px.scatter(df, x="sepal_width", y="sepal_length",symbol="species" ,color="species", size='petal_length',hover_data=['petal_width'], hover_name="species",text="species_id",title="鸢尾花分类展示",animation_frame="species",range_x=[1.5,4.5],range_y=[4,8.5])
fig.show()df = px.data.gapminder().query("country=='China'")
# Index(['country', 'continent', 'year', 'lifeExp', 'pop', 'gdpPercap', 'iso_alpha', 'iso_num'],dtype='object')
#     country continent  year  ...    gdpPercap  iso_alpha  iso_num
# 288   China      Asia  1952  ...   400.448611        CHN      156
# 289   China      Asia  1957  ...   575.987001        CHN      156
# 290   China      Asia  1962  ...   487.674018        CHN      156
# plotly.express.line(data_frame=None, x=None, y=None,
# line_group=None, color=None, line_dash=None,
# hover_name=None, hover_data=None, custom_data=None, text=None,
# facet_row=None, facet_col=None, facet_col_wrap=0,
# facet_row_spacing=None, facet_col_spacing=None,
# error_x=None, error_x_minus=None, error_y=None, error_y_minus=None,
# animation_frame=None, animation_group=None,
# category_orders=None, labels=None, orientation=None,
# color_discrete_sequence=None, color_discrete_map=None,
# line_dash_sequence=None, line_dash_map=None,
# log_x=False, log_y=False,
# range_x=None, range_y=None,
# line_shape=None, render_mode='auto', title=None,
# template=None, width=None, height=None)
# 显示中国的人均寿命
fig = px.line(df, x="year", y="lifeExp", title='中国人均寿命')
fig.show()# 以不同颜色显示亚洲各国的人均寿命
df = px.data.gapminder().query("continent == 'Asia'")
fig = px.line(df, x="year", y="lifeExp", color="country", hover_name="country")
fig.show()# line_group="country" 达到按国家去重的目的
df = px.data.gapminder().query("continent != 'Asia'") # remove Asia for visibility
fig = px.line(df, x="year", y="lifeExp", color="continent",line_group="country", hover_name="country")
fig.show()# bar图
df = px.data.gapminder().query("country == 'China'")
fig = px.bar(df, x='year', y='lifeExp')
fig.show()df = px.data.gapminder().query("continent == 'Asia'")
fig = px.bar(df, x='year', y='lifeExp',color="country" )
fig.show()df = px.data.gapminder().query("country == 'China'")
fig = px.bar(df, x='year', y='pop',hover_data=['lifeExp', 'gdpPercap'], color='lifeExp',labels={'pop':'population of China'}, height=400)
fig.show()fig = px.bar(df, x='year', y='pop',hover_data=['lifeExp', 'gdpPercap'], color='pop',labels={'pop':'population of China'}, height=400)
fig.show()df = px.data.medals_long()
# #         nation   medal  count
# # 0  South Korea    gold     24
# # 1        China    gold     10
# # 2       Canada    gold      9
# # 3  South Korea  silver     13
# # 4        China  silver     15
# # 5       Canada  silver     12
# # 6  South Korea  bronze     11
# # 7        China  bronze      8
# # 8       Canada  bronze     12
fig = px.bar(df, x="nation", y="count", color="medal", title="Long-Form Input")
fig.show()# 气泡图
df = px.data.gapminder()
# X轴以对数形式展现
fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp",size="pop",color="continent",hover_name="country", log_x=True, size_max=60)
fig.show()# X轴以标准形式展现
fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp",size="pop",color="continent",hover_name="country", log_x=False, size_max=60)
fig.show()# 饼状图
px.data.gapminder().query("year == 2007").groupby('continent').count()
#            country  year  lifeExp  pop  gdpPercap  iso_alpha  iso_num
# continent
# Africa          52    52       52   52         52         52       52
# Americas        25    25       25   25         25         25       25
# Asia            33    33       33   33         33         33       33
# Europe          30    30       30   30         30         30       30
# Oceania          2     2        2    2          2          2        2
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values='pop', names='country',title='Population of European continent')
fig.show()df.loc[df['pop'] < 10000000, 'country'] = 'Other countries'
fig = px.pie(df, values='pop', names='country', title='Population of European continent',hover_name='country',labels='country')
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()df.loc[df['pop'] < 10000000, 'country'] = 'Other countries'
fig = px.pie(df, values='pop', names='country', title='Population of European continent',hover_name='country',labels='country', color_discrete_sequence=px.colors.sequential.Blues)
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()# 二维面积图
df = px.data.gapminder()
fig = px.area(df, x="year", y="pop", color="continent", line_group="country")
fig.show()fig = px.area(df, x="year", y="pop", color="continent", line_group="country",color_discrete_sequence=px.colors.sequential.Blues)
fig.show()df = px.data.gapminder().query("year == 2007")
fig = px.bar(df, x="pop", y="continent", orientation='h',hover_name='country',text='country',color='continent')
fig.show()# 甘特图
import pandas as pd
df = pd.DataFrame([dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Completion_pct=50, Resource="Alex"),dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15',Completion_pct=25, Resource="Alex"),dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Completion_pct=75, Resource="Max")
])
fig = px.timeline(df, x_start="Start", x_end="Finish", y="Task", color="Completion_pct")
fig.update_yaxes(autorange="reversed")
fig.show()fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Resource")
fig.update_yaxes(autorange="reversed")
fig.show()# 玫瑰环图
df = px.data.tips()
#      total_bill   tip     sex smoker   day    time  size
# 0         16.99  1.01  Female     No   Sun  Dinner     2
# 1         10.34  1.66    Male     No   Sun  Dinner     3
# 2         21.01  3.50    Male     No   Sun  Dinner     3
# 3         23.68  3.31    Male     No   Sun  Dinner     2
# 4         24.59  3.61  Female     No   Sun  Dinner     4
fig = px.sunburst(df, path=['day', 'time', 'sex'], values='total_bill')
fig.show()import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.sunburst(df, path=['continent', 'country'], values='pop',color='lifeExp', hover_data=['iso_alpha'],color_continuous_scale='RdBu',color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.show()df = px.data.gapminder().query("year == 2007")
fig = px.sunburst(df, path=['continent', 'country'], values='pop',color='pop', hover_data=['iso_alpha'],color_continuous_scale='RdBu')
fig.show()# treemap图
import numpy as np
df = px.data.gapminder().query("year == 2007")
df["world"] = "world" # in order to have a single root node
fig = px.treemap(df, path=['world', 'continent', 'country'], values='pop',color='lifeExp', hover_data=['iso_alpha'],color_continuous_scale='RdBu',color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.show()fig = px.treemap(df, path=['world', 'continent', 'country'], values='pop',color='pop', hover_data=['iso_alpha'],color_continuous_scale='RdBu',color_continuous_midpoint=np.average(df['lifeExp'], weights=df['pop']))
fig.show()fig = px.treemap(df, path=['world', 'continent', 'country'], values='pop',color='lifeExp', hover_data=['iso_alpha'],color_continuous_scale='RdBu')
fig.show()fig = px.treemap(df, path=[ 'continent', 'country'], values='pop',color='lifeExp', hover_data=['iso_alpha'],color_continuous_scale='RdBu')
fig.show()fig = px.treemap(df, path=[ 'country'], values='pop',color='lifeExp', hover_data=['iso_alpha'],color_continuous_scale='RdBu')
fig.show()# 桑基图
tips = px.data.tips()
fig = px.parallel_categories(tips, color="size",color_continuous_scale=px.colors.sequential.Inferno)
fig.show()

关于Python可视化Dash工具—plotly基本图形相关推荐

  1. 关于Python可视化Dash工具

    Dash是基于Flask的Python可视化工具,严格说来由三个部分组成,首先是Flask提供了标准web环境,再次是plotly这个图表可视化工具,最后是与dash相配套的html.图表等交互式组件 ...

  2. python可视化图表工具_酷炫的可视化图表工具来帮忙 深度评测五大Python数据可视化工具...

    原标题:酷炫的可视化图表工具来帮忙 深度评测五大Python数据可视化工具 不少Python用户的一大诉求是做出各种酷炫的可视化图表,而这就需要了解清楚工具特色,才好在制作不同类型图表顺利找到适合自己 ...

  3. python可视化界面工具_8个流行的 Python可视化工具包,你喜欢哪个?

    点击上方"Python编程开发",选择"星标或者置顶" 一起高效学习Python编程开发! 编译:机器之心,作者:Aaron Frederick 喜欢用 Pyt ...

  4. python可视化开源工具_这5款Python可视化神器,总有一款适合你!

    我们都知道视觉是人们很重要的一种感官,而Python中可视化,在数据相关的研发中也起到"一木支危楼 "的作用.如果从直接查看离线存储在各类数据库中杂乱无章的数据,会让人瞬间感到崩溃 ...

  5. 相见恨晚的Python可视化配色工具

    来源:pythonic生物人 有小伙伴说python可视化自带颜色很丑,那您一定是没遇到palettable,palettable是一个纯python写的颜色条(Colormap)库,汇集了大量知名可 ...

  6. matplotlib画图使用python可视化colorbar工具自定义颜色

    python matplotlib画图使用colorbar工具自定义颜色 colorbar(draw colorbar without any mapple/plot) 自定义colorbar可以画出 ...

  7. Python可视化之Matplotlib绘制高级图形对数图、频谱图、矢量场流线图、互关图

    1.对数图 便于观察图形之间变化的情况 from matplotlib import pyplot as plt import numpy as np x = np.linspace(1,100) y ...

  8. python中plotly_Python绘图工具Plotly的简单使用

    1.Plotly被称为史上最好的绘图工具之一,为了更好的展示金融数据的复杂性. Plotly的官方网站为:https://plot.ly/ python量化的关键是金融数据可视化,无论是传统的K线图, ...

  9. Python可视化(matplotlib)在图像中添加文本和标记(Text and Annotation)

    Python可视化(matplotlib)在图像中添加文本和标记(Text and Annotation) 目录 Python可视化(matplotlib)在图形中添加文本和标记(Text and A ...

最新文章

  1. xtraTabbedMdiManager 双击最大化和关闭后返回主界面 z
  2. 口令即漏洞 放弃它吧
  3. 使用xshell5 从CentOS主机download资料
  4. Hibernate Criterion
  5. linux c select 服务器源码 简介
  6. html引入外部css_CSS 三种基础选择器
  7. 你的心事我全知晓——心情日记小程序丨实战
  8. 程序员自我提高情绪10招
  9. DM8168 TILER(2)
  10. 八种常用的排序算法(转)
  11. 获取Repeater控件里动态声称的控件的值
  12. STARK论文记录(2021CVPR):Learning Spatio-Temporal Transformer for Visual Tracking
  13. python机器人编程前景_机器人编程挑战python
  14. 科学家发明创可贴式MP3靠人体热量工作
  15. Windows触控手势
  16. 倒三角打印乘法口诀python_Python打印乘法口诀表
  17. 小米手机混淆升级崩溃记录与解决
  18. 修改树莓派的CoD(即蓝牙识别类型)
  19. 外骨骼设备系列4:人工智能学院派精英打造美国特种部队唯一合作的“钢铁侠”
  20. 谷歌安卓以AAB替换APK安装包

热门文章

  1. 背叛的下场,你敢不敢看
  2. 不顺本也正常,斗志不可磨灭
  3. 传统就没新意? 年货节“走马灯”刷新H5创意理念
  4. Scratch3.0----函数(1)
  5. 【人工智能 Open AI】解释一下 Raft 分布式一致性协议算法,并用伪代码实例说明。
  6. 【编程实践】Raft 算法的原理 go代码实例
  7. 基于AM5728 linux开源ethercat运动控制一体机解决方案
  8. 香槐路的香槐花,匆匆四年无归期。
  9. 《软件开发工具》(第二章)
  10. 被误解的鸟枪换炮:实体资产通证化没那么容易