Detailed explanation of plotly basic graphic example of Python visualization Dash tool

  • 2021-10-13 08:13:00
  • OfStack

Plotly Express is an advanced package of Plotly. py, with a large number of practical and modern drawing templates built in. Users only need to call simple API functions to quickly generate beautiful interactive charts, which can meet more than 90% of application scenarios.

With the help of several sample libraries provided by Plotly and Express, this paper realizes the basic graphics such as scatter chart, line chart, pie chart, histogram, bubble chart, Sankey chart, rose ring chart, stacking chart, 2-dimensional area chart and Gantt chart.

Code Sample


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)
#  With sepal_width , sepal_length Make standard scatter plot 
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.show()
 
 
# With iris type -species As a distinguishing sign of different colors  color
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()
 
# Append petal_length As the scatter size, the displacement bubble diagram  size
fig = px.scatter(df, x="sepal_width", y="sepal_length",
         color="species",size='petal_length')
fig.show()
 
# Append petal_width As an extra column, it is displayed as extra data in the hover tooltip  hover_data
fig = px.scatter(df, x="sepal_width", y="sepal_length",
         color="species", size='petal_length',
         hover_data=['petal_width'])
fig.show()
 
# With iris type -species Shape of area dispersion point  symbol
fig = px.scatter(df, x="sepal_width", y="sepal_length",
         symbol="species" ,color="species", 
         size='petal_length',
         hover_data=['petal_width'])
fig.show()
 
# Append petal_width As an extra column, it is displayed in bold in the hover tooltip.  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()
 
# Coded by iris type -species_id Text value as scatter  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()
 
# Append chart title  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=" Classification and display of iris ")
fig.show()
 
# With iris type -species As an animation playback mode  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=" Classification and display of iris ",
         animation_frame="species")
fig.show()
 
# Fixed X , Y Maximum value and minimum value range range_x , range_y To prevent animation from exceeding numerical display when playing 
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=" Classification and display of iris ",
         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)
#  It shows that life expectancy in China 
fig = px.line(df, x="year", y="lifeExp", title=' Life expectancy in China ')
fig.show()
 
#  Show the life expectancy of Asian countries in different colors 
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"  Achieve the purpose of removing weight according to 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 Figure 
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()
 
#  Bubble chart 
df = px.data.gapminder()
# X The axis is presented in logarithmic form 
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 The axes are presented in standard form 
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()
 
#  Pie chart 
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()
 
# 2 Dimensional area map 
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()
 
#  Gantt chart 
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()
 
#  Rose ring diagram 
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 Figure 
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()
 
#  Sankey diagram 
tips = px.data.tips()
fig = px.parallel_categories(tips, color="size",
               color_continuous_scale=px.colors.sequential.Inferno)
fig.show()

Related articles: