欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于Python可视化Dash工具之plotly基本图形示例详解

程序员文章站 2022-09-06 14:58:34
plotly express是对 plotly.py 的高级封装,内置了大量实用、现代的绘图模板,用户只需调用简单的api函数,即可快速生成漂亮的互动图表,可满足90%以上的应用场景。本文借助plot...

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基本图形示例详解的文章就介绍到这了,更多相关python plotly基本图形内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!