Cool! Plotly: Play a pie chart

Two previous posts on Plotly:

  • Introduction: Cool! Love advanced visualization artifact Plotly_Express

  • Scatter plot: Cool! Visualization of the Plotly play scatter diagram

The most important feature of Plotly is the small amount of code, good color and dynamic visualization. Plotly will be serialized in the future.

Import libraries

The environment used in this article:

  • Python3.7.5
  • jupyter notebook
  • plotly4.11.0
  • Plotly – express0.4.1
import pandas as pd
import numpy as np
import plotly_express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
Copy the code

There are two main ways to make pie charts:

  1. Plotly_express: px. Pie
  2. Plotly. Graph_objects: go. Pie

Implement pie chart based on Plotly_express

The pie chart

Using the simulated data to generate the basic pie chart, the number of 5 fruits in a fruit shop is generated:

fruit = pd.DataFrame({
    "name": [The word "apple"."Banana"."Pear"."Pineapple"."Grapes"]."number": [1000.800.600.2000.2500]})

fruit
Copy the code

fig = px.pie(fruit,names="name",values="number")
fig.show()
Copy the code

The default display is the percentage and the category name on the right

Add the title

fig = px.pie(fruit,
             names="name",
             values="number",
             title="Percentage of fruit"  # add title
            )
fig.show()
Copy the code

⚠️ : The title defaults to the upper right corner. Sometimes we want the title to be centered. How do we do that?

fig = px.pie(fruit,
             names="name",
             values="number"
            )

fig.update_layout(
    title={   Set the name and location of the entire title
        "text":"Percentage of fruit"."y":0.96.# y
        "x":0.5.# x value
        "xanchor":"center".# relative position of x and y axes
        "yanchor":"top"  
    }
)

fig.show()
Copy the code

Change the pie chart color

Now that we have seen the default color of Plotly_express from the top pie chart, let’s change the color of the pie chart:

1. Change the color by using the color parameter:

fig = px.pie(fruit,
             names="name",
             values="number",
             color="number"
            )
fig.show()
Copy the code

2. Set the color_discrete_sequence parameter:

fig = px.pie(fruit,
             names="name",
             values="number".# Different colors: RdBu, Peach
             color_discrete_sequence=px.colors.sequential.RdBu  You only need to change the final RdBu
            )
fig.show()
Copy the code

The pie chart above shows 3 different colors

3. Set the color using the dictionary form:

fig = px.pie(fruit,
             names="name",
             values="number",
             color="name",
             color_discrete_map={   # dictionary form set color
                 'grapes':'lightcyan'.'pineapple':'cyan'.'apple':'royablue'.'banana':'darkblue'.'pear':'red'}
            )
fig.show()
Copy the code

Text Message Setting

In many cases we want to set the text information displayed in the pie chart

1, the default pie chart is to display percentages, change the displayed data:

fig = px.pie(fruit,names="name",values="number")

fig.update_traces(
    textposition='inside'.# text display position: ['inside', 'outside', 'auto', 'none']
    textinfo='percent+label'
)

fig.show()
Copy the code

The pie chart above shows the names of various fruits: name + percentage

fig = px.pie(fruit,names="name",values="number")

fig.update_traces(
    textposition='inside',
    textinfo='percent+value'
)

fig.show()
Copy the code

The pie chart above shows: number + percentage

2, change the position of the display data, the default is in the sector area, can be set to display outside:

fig = px.pie(fruit,names="name",values="number")

fig.update_traces(
    textposition='outside'.# display outside
    textinfo='label+value'  Tag name + data
)

fig.show()
Copy the code

3. Text hiding

For example, the pie chart that comes with Plotly’s built-in data:

df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")

Other countries
df.loc[df["pop"] < 2.e6."country"] = "Other countries"  

fig = px.pie(df, 
             names="country",
             values="pop", 
             title="Population of Eurpean contient")
fig.show()
Copy the code

Some data with too low a percentage that we want to hide from display:

fig = px.pie(gap, values='pop', names='country')

fig.update_traces(textposition='inside') # text display position: ['inside', 'outside', 'auto', 'none']

fig.update_layout(uniformtext_minsize=15.# Minimum text message value
                  uniformtext_mode='hide'  # 3 modes: [False, 'hide', 'show']

                 )
fig.show()
Copy the code

Set UniformText_mode to False:

4. Display direction of text information

Text information is displayed in three directions: horizontal, radial and tangential. The default is horizontal

The default effect is level

fig = px.pie(fruit,names="name",values="number")

fig.update_traces(
    textposition='inside'.# 'inside','outside','auto','none'
    textinfo='percent+label',
    insidetextorientation='radial'   Horizontal, radial, tangential
)

fig.show()
Copy the code

Donut Chart

The doughnut diagram is done by hollowing out the middle, using the parameter hole:

fig = px.pie(fruit,
             names="name",
             values="number",
             hole=0.3.# Set the ratio of hollow circles in the middle: 0-1
             title="Percentage of fruit"
            )
fig.show()
Copy the code

Implemented based on go.pie

Basic pie chart making

import plotly.graph_objects as go

name=fruit["name"].tolist()
value=fruit["number"].tolist()  

fig = go.Figure(
    data=[go.Pie(
        labels=name,
        values=value)
         ]
)

fig.show()
Copy the code

Personalized border Settings

import plotly.graph_objects as go

name=fruit["name"].tolist()
value=fruit["number"].tolist()  
colors = ['gold'.'mediumturquoise'.'darkorange'.'lightgreen'.'cyan']

# drawing
fig = go.Figure(
    data=[go.Pie(
        labels=name,
        values=value)
         ]
)

Update # traces
fig.update_traces(
    hoverinfo='label+percent',
    textinfo='value',
    textfont_size=20,
    marker=dict(colors=colors, 
                line=dict(color='# 000000',
                          width=2)))

fig.show()
Copy the code

Text orientation setting

import plotly.graph_objects as go

labels = ['Oxygen'.'Hydrogen'.'Carbon_Dioxide'.'Nitrogen']
values = [4500.2500.1053.500]

fig = go.Figure(data=[go.Pie(
    labels=labels, 
    values=values, 
    textinfo='label+percent',
    insidetextorientation='radial'
)])  # is also 3 orientations

fig.show()
Copy the code

Donuts figure

import plotly.graph_objects as go

labels = ['Oxygen'.'Hydrogen'.'Carbon_Dioxide'.'Nitrogen']
values = [3000.1500.1000.2500]

fig = go.Figure(data=[go.Pie(
    labels=labels, 
    values=values, 
    hole=4.)])

fig.show()
Copy the code

Sectorial detachment

import plotly.graph_objects as go

labels = ['Oxygen'.'Hydrogen'.'Carbon_Dioxide'.'Nitrogen']
values = [3000.1000.4000.2500]

fig = go.Figure(data=[go.Pie(
    labels=labels, 
    values=values, 
    pull=[0.3.0.1.0.0]  # Set the escape parameter
)])

fig.show()
Copy the code

Multi pie chart making

This is an example from the official website, how to set up multiple pie charts

from plotly.subplots import make_subplots

labels = ["US"."China"."European Union"."Russian Federation"."Brazil"."India"."Rest of World"]

# Create subgraph: 'domain' denotes pie chart
fig = make_subplots(
    rows=1, 
    cols=2, 
    specs=[[{'type':'domain'}, 
            {'type':'domain'}]])

# Add two subgraphs
fig.add_trace(go.Pie(
    labels=labels, 
    values=[16.15.12.6.5.4.42],
    name="GHG Emissions"),
              row=1, 
              col=1)

fig.add_trace(go.Pie(
    labels=labels, 
    values=[27.11.25.8.1.3.25], 
    name="CO2 Emissions"),
              1.2)   The row and col arguments can be omitted

Make a hollow doughnut using the hole parameter
fig.update_traces(hole=4., hoverinfo="label+percent+name")

fig.update_layout(
    title_text="Global Emissions 1990-2011".# The name of the graph
    # Annotate donuts
    annotations=[dict(text='GHG', x=0.15, y=0.5, font_size=20, showarrow=True),
                 dict(text='CO2', x=0.82, y=0.5, font_size=15, showarrow=False)])

fig.show()
Copy the code

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# Set the color of different blocks by RGB
night_colors = ['rgb(200, 75, 126)'.'rgb(18, 36, 37)'.'rgb(134, 53, 101)'.'rgb(136, 55, 57)'.'rgb(206, 4, 4)']
sunflowers_colors =  ['rgb(200, 75, 126)'.'rgb(18, 36, 37)'.'rgb(134, 53, 101)'.'rgb(136, 55, 57)'.'rgb(206, 4, 4)']
irises_colors =  ['rgb(200, 75, 126)'.'rgb(18, 36, 37)'.'rgb(134, 53, 101)'.'rgb(136, 55, 57)'.'rgb(206, 4, 4)']
cafe_colors =   ['rgb(200, 75, 126)'.'rgb(18, 36, 37)'.'rgb(134, 53, 101)'.'rgb(136, 55, 57)'.'rgb(206, 4, 4)']

# set subgraph number and type spec
specs = [[{'type':'domain'},   Pie chart domain
          {'type':'domain'}], 
         
         [{'type':'domain'}, 
          {'type':'domain'}]]

fig = make_subplots(rows=2, cols=2, specs=specs)  # 2 rows, 2 columns

# Add 4 pie charts

labels = ['1st'.'2nd'.'3rd'.'4th'.'5th']

fig.add_trace(go.Pie(labels=labels, 
                     values=[38.27.18.10.7], 
                     name='Pie one',
                     marker_colors=night_colors), 1.1)

fig.add_trace(go.Pie(labels=labels, 
                     values=[28.26.21.15.10], 
                     name='Pie two',
                     marker_colors=sunflowers_colors
                    ), 1.2)

fig.add_trace(go.Pie(labels=labels, 
                     values=[8.19.16.14.13], 
                     name='Pie three',
                     marker_colors=irises_colors), 2.1)

fig.add_trace(go.Pie(labels=labels, 
                     values=[31.24.19.18.8], 
                     name='Pie four',
                     marker_colors=cafe_colors), 2.2)

# 
fig.update_traces(hoverinfo='label+percent+name', textinfo='value')  # ['label', 'text', 'value', 'percent']

fig.update(layout_title_text='Plotly draw 4 sub-pie charts'.# set the title
           layout_showlegend=True)   Whether to display the legend on the right side

fig = go.Figure(fig)
fig.show()
Copy the code

Sunrise map making

The rising sun diagram represents the size relationship between data hierarchies:

1. Basic rising Sun

import plotly.express as px
data = dict(
    # Set each element and its parent element (the same number, note the innermost empty set)
    character=["Eve"."Cain"."Seth"."Enos"."Noam"."Abel"."Awan"."Enoch"."Azura"],
    parent=[""."Eve"."Eve"."Seth"."Seth"."Eve"."Eve"."Awan"."Eve" ],
    value=[10.14.12.10.4.6.2.4.3])

fig =px.sunburst(
    data,
    names='character',
    parents='parent',
    values='value',
)
fig.show()
Copy the code

2. Sunrise diagram based on DataFrame long table

fig = px.sunburst(tips,
                  path=['day'.'time'.'sex'].# # # # # # # # # # # # # # # #
                  values='total_bill'
                 )
fig.show()
Copy the code

2. Change the color of the rising sun

df = px.data.tips()

fig = px.sunburst(
  df, 
  path=['time'.'sex'.'day'],
  values='total_bill', 
  color='day')    Set the color parameter

fig.show()
Copy the code

3. Change by color_continuous_scale parameter

# Set the color of the sunrise image

fig = px.sunburst(
    tips,
    path=['day'.'time'.'sex'].# # # # # # # # # # # # # # # #
    values='total_bill',
    color='total_bill',
    hover_data=['total_bill'],
    color_continuous_scale='RdBu'.# color_continuous_midpoint = np. Business (tips [" total_bill "] * 1.5)
                 )
fig.show()
Copy the code

Parameter Memo

Based on the plotly. Express.pie parameter

plotly.express.pie(
  data_frame=None.# Drawing data
  names=None.# Name of each sector
  values=None.# Value size
  color=None.# color
  color_discrete_sequence=None.# Color continuity Settings
  color_discrete_map=None.# set by dictionary type
  hover_name=None.Hover over the display of the name and data
  hover_data=None, 
  custom_data=None, 
  labels=None.Dict with string keys and string values, defaults to {}. This parameter is used to modify the column names displayed on the chart
  title=None.# titles
  template=None.# string or Plotly. Py template object with three built-in Plotly themes: Plotly, plotly_white, and plotly_dark
  width=None.# Length, width, transparency
  height=None, 
  opacity=None, 
  hole=None) # Hollow ratio
Copy the code

You cottage, a sweet cottage. Cabin master, one hand code for survival, one hand cooking spoon to enjoy life, welcome your presence 😃