Plotly play bar diagram for visualization

This article is part 5 of Plotly Mapping, which focuses on how to draw a bar chart using Plotly. Bar chart is a kind of chart with high frequency in visualization, which can intuitively show the size distribution of data and is frequently used in my own work. This article will explain in detail how to make bar charts and horizontal bar charts.

The first four Plotly articles are:

  • Cool! Love advanced visualization artifact Plotly_Express
  • Plotly play scatter chart
  • Plotly plays a pie chart
  • Plotly plays a funnel

Import libraries

First of all, we need to import some common libraries that we need for drawing

import pandas as pd
import numpy as np

# Two interfaces
import plotly_express as px
import plotly.graph_objects as go
Copy the code

Drawing is still done in two ways:

  • Plotly_express: px.
  • Plotly. Graph_objects: go

Implement the bar chart based on PX

Base bar chart

The simulation generates the data needed for a simple drawing

df1 = pd.DataFrame({
    "name": ["Xiao Ming"."Little red"."Zhou Ming"."Red"."Zhang"]."age": [20.28.18.25.36]."score": ["150"."170"."160"."168"."154"]
})

df1
Copy the code

fig = px.bar(df1,x="name",y="age")
fig.show()
Copy the code

Add color parameter color:

fig = px.bar(df1,
             x="name",
             y="age",
             color="age"   # color parameter
            )
fig.show()
Copy the code

Grouping bar charts based on long tables

df2 = pd.DataFrame({
    "Name": ["Xiao Ming"."Little red"."Zhang"."Xiao Ming"."Little red"."Zhang"."Xiao Ming"."Little red"."Zhang"]."Subject": ["Chinese"."Chinese"."Chinese"."Mathematics"."Mathematics"."Mathematics"."English"."English"."English"]."Score": [58.78.84.90.71.90.64.84.69]
})

df2
Copy the code

fig = px.bar(df2,
            x="Name",
            y="Score",
            color="Subject")
fig.show()
Copy the code

Grouping bar chart based on wide table

Wide table format mainly refers to a large number of fields

df3 = pd.DataFrame({
    "Name": ["Xiao Ming"."Little red"."Zhang"]."Chinese": [58.78.84]."Mathematics": [90.71.90]."English": [64.84.69]
})

df3
Copy the code

fig = px.bar(df3,
            x="Name",
            y=["Chinese"."Mathematics"."English"],
            title="Student performance comparison"  # add title
            )
fig.show()
Copy the code

Chart personality Settings

1. Change the color of the graph: add color parameters

fig = px.bar(df1,
             x="name",
             y="age",
             color="age"  # add color argument
            )
fig.show()
Copy the code

Take a look at an example of tipping in your own dataset:

fig = px.bar(df4,
             x="sex",
             y="total_bill",
             color="smoker"   # parameters
            )

fig.show()
Copy the code

2. Set the hover information for the chart: hover_data:

fig = px.bar(df1,
             x="name",
             y="age",
             color="age".# add color argument
             hover_data = ['score']   # hover parameter
            )
fig.show()
Copy the code

3. Set the x axis label tilt

information = pd.DataFrame({
    "days": ["Monday, March 1, 2021"."Tuesday, March 2, 2021"."Wednesday, March 3, 2021"."Thursday, March 4, 2021"And then to decide,"Friday, March 5, 2021"]."number": [400.700.300.500.800]
})

information
Copy the code

The default is horizontal:

fig = px.bar(information,x="days",y="number")
fig.show()   # Default horizontal display
Copy the code

If we add the argument width, height is shown to the right:

fig = px.bar(information,
             x="days",
             y="number",
             width=600,
             height=600)
fig.show()   The width, height parameters are displayed to the right
Copy the code

Add xaxis_tickAngle to set the tilt Angle:

fig = px.bar(information,x="days",y="number")
fig.update_layout(xaxis_tickangle=-45)   # Tilt Angle Settings
fig.show()   The result is a tilt to the left
Copy the code

Even if we add width=600,height=600 is tilted to the left:

fig = px.bar(information,x="days",y="number",width=600,height=600)
fig.update_layout(xaxis_tickangle=-45)   # Tilt Angle Settings

fig.show()   The result is a tilt to the left
Copy the code

Bar chart mode Settings

There are mainly four bar chart display modes:

  • Stack stack:
  • Group: group
  • Covered overlay:
  • Relative: relative
fig = px.bar(df4,
             x="sex",
             y="total_bill",
             color="smoker",
             barmode="stack"  # ['stack', 'group', 'overlay', 'relative']
            )

fig.show()
Copy the code

Display differences in 4 different modes:

Polyhedral bar chart

Let’s take the built-in tip data for example:

fig = px.bar(df4,   # With drawing data
             x="sex".# x
             y="total_bill".# y
             color="smoker".# color Settings
             barmode="group".# One of the 4 patterns of the bar chart
             facet_row="time".Line #
             facet_col="day".# column
             category_orders={
                 "day": ["Thur"."Fri"."Sat"."Sun"]."time": ["Lunch"."Dinner"]   # Set the classification order
                             }
            )
fig.show()
Copy the code

Note the meaning of each parameter

Implement bar graph based on GO

Base bar chart

Self-built data sets:

fig = go.Figure(
    data = (
        go.Bar(x=df1["name"].tolist(),  # X-axis data
               y=df1["score"].tolist()  # Y-axis data
              )
    )
)

fig.show()
Copy the code

Grouping bar chart

There are also 4 different bar chart modes to choose from:

  • Stack stack:
  • Group: group
  • Covered overlay:
  • Relative: relative
fig = go.Figure(data=[
    go.Bar(name='Ming', x=["Chinese"."Mathematics"."English"], y=[120.104.93]),
    go.Bar(name='little red', x=["Chinese"."Mathematics"."English"], y=[101.88.109]])Select 1 from 4 for bar chart mode
fig.update_layout(barmode='group')  # ['stack', 'group', 'overlay', 'relative']

fig.show()
Copy the code

Set the hoverText hover message

name = ['Product A'.'Product B'.'Product C']
number = [200.500.300]

fig = go.Figure(data=[go.Bar(x=name, 
                             y=number,
                             hovertext=['20% market share '.'50% market share '.'30% market share '])])

fig.update_traces(marker_color='RGB (158202225)..# marker color
                  marker_line_color='RGB (8,48,107)'.# Line color
                  marker_line_width=1.5.# line width
                  opacity=0.6)  # transparency

fig.update_layout(title_text='3 product market share ')

fig.show()
Copy the code

Display data information

Four modes are displayed:

  • Auto: automatically
  • Inside the inside:
  • Outside: external
  • None: no
name = ['Product A'.'Product B'.'Product C']
number = [200.500.300]

fig = go.Figure(data=[go.Bar(x=name, 
                             y=number,
                             text=number,  # display data for number
                             textposition="auto"  # ['inside', 'outside', 'auto', 'none']
                             )])

fig.update_layout(title_text='Market quantity of 3 products')

fig.show()
Copy the code

Format text display mode

import plotly.express as px

gap = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")

gap.head()
Copy the code

fig = px.bar(gap, 
             x='country',
             y='pop', 
             text='lifeExp')

fig.update_traces(texttemplate='%{text:.2s}'.# Integer number of digits to display: 2 bits in the example
                  textposition='outside')   # text display position: ['inside', 'outside', 'auto', 'none']

fig.update_layout(uniformtext_minsize=8.Display text font size
                  uniformtext_mode='show')  [False, 'hide', 'show']

fig.show()
Copy the code

The X-axis label is tilted

import plotly.graph_objects as go

months = ['Jan'.'Feb'.'Mar'.'Apr'.'May'.'Jun'.'Jul'.'Aug'.'Sep'.'Oct'.'Nov'.'Dec']

Generate the canvas object
fig = go.Figure()  


# Add multiple graphics tracks
fig.add_trace(go.Bar(
    x=months,
    y=[20.14.25.16.18.22.19.15.12.16.14.17],
    name=Products' A ',
    marker_color='lightblue'  # Different representations of color
))

fig.add_trace(go.Bar(
    x=months,
    y=[19.14.22.14.16.19.15.14.10.12.12.16],
    name=Products' B ',
    marker_color='#af0010'
))

fig.update_layout(barmode='group'.# Bar chart pattern
                  xaxis_tickangle=-45   # Tilt Angle
                 )
fig.show()
Copy the code

Single bar chart Settings

We still have our own data set:

fig = go.Figure(data=[go.Bar(
    x=df1["name"].tolist(),  # name on the X-axis
    y=df1["score"].tolist(), The fraction is the Y-axis
    marker_color=colors  # Color Settings: colors above
)])

fig.update_layout(title_text="Final grade")

fig.show()
Copy the code

Bar chart width Settings

# If not set, each bar chart is the same width

fig = go.Figure(data=[go.Bar(
    x=df1["name"].tolist(),  # name on the X-axis
    y=df1["score"].tolist(), The fraction is the Y-axis
)])

fig.update_layout(title_text="Final grade")

fig.show()
Copy the code

By default, each column is the same width:

We give each column a different width:

fig = go.Figure(data=[go.Bar(
    x=df1["name"].tolist(),  # name on the X-axis
    y=df1["score"].tolist(), The fraction is the Y-axis
    width=[1.0.8.0.4.1.2.0.4]  # width set
)])

fig.update_layout(title_text="Final grade")

fig.show()
Copy the code

Change the bar chart reference position

import plotly.graph_objects as go

years = ['2018'.'2019'.'2020']

fig = go.Figure()

fig.add_trace(go.Bar(
    x=years, 
    y=[2000.3000.5000].Array ([2000, 3000, 5000]) * (-1)
    base=[-2000, -3000, -5000].# Baseline Settings
    marker_color='crimson',
    name=Merchants' A '))

fig.add_trace(go.Bar(
    x=years, 
    y=[3000.4000.2000],
    base=0.# Default baseline Settings
    marker_color='lightslategrey',
    name=Merchants' B '
))

fig.show()
Copy the code

Legend position and color

Set the position and color of the legend:

import plotly.graph_objects as go

subjects = ["Chinese"."Mathematics"."English"."Physical"."Chemistry"."Creatures"]

fig = go.Figure()
fig.add_trace(go.Bar(
    x=subjects,   # X-axis and Y-axis data
    y=[90.85.78.90.99.80],                
    name='Ming'.# legend name
    marker_color='rgb(15, 83, 109)'  # This group of data color
                
))

fig.add_trace(go.Bar(
    x=subjects,               
    y=[80.89.68.100.78.90],               
    name='little red',               
    marker_color='rgb(180, 118, 255)'
                ))

fig.update_layout(
    title='Final grade Comparison'.# The title of the entire graph
    xaxis_tickfont_size=12.# X-axis font size
    yaxis=dict(
        title='results'.# the title of the Y-axis
        titlefont_size=16.# title size
        tickfont_size=12.# the magnitude of the Y-axis
    ),
    legend=dict(
        x=0.# Legend position
        y=1.# bgcolor=' rGBA (255, 255, 255, 0)', # legend background color
        bordercolor='rgba(2, 255, 255, 0)'   # Edge color
    ),
    barmode='group'.# Bar chart pattern
    bargap=0.4.# Distance between groups
    bargroupgap=0.2  # Group distance
)
fig.show()
Copy the code

Relative understanding of patterns

import plotly.graph_objects as go

x = [1.2.3.4]

fig = go.Figure()
fig.add_trace(go.Bar(x=x, y=[1.4.9.2]))
fig.add_trace(go.Bar(x=x, y=[6, -9, -1.5.4]))
fig.add_trace(go.Bar(x=x, y=[-10, -3.4.5, -8]))
fig.add_trace(go.Bar(x=x, y=[-1.3, -3, -4]))

fig.update_layout(
    barmode='relative'.# Relative to the initial position
    title_text='Relative pattern understanding')

fig.show()
Copy the code

Stacking patterns

import plotly.graph_objects as go

subjects=['Chinese'.'mathematics'.'English']

fig = go.Figure(go.Bar(
    x=subjects, 
    y=[69.71.120], 
    name='Ming'))

fig.add_trace(go.Bar(
    x=subjects, 
    y=[64.89.116], 
    name='little red'))

fig.add_trace(go.Bar(
    x=subjects, 
    y=[76.104.70], 
    name='Joe'))

fig.update_layout(
    barmode='stack'.# Stack mode
    xaxis={'categoryorder':'total descending'})  # Category ascending, category descending, total descending, total descending

fig.show()
Copy the code

Multiple groups share the X-axis

import plotly.graph_objects as go

x = [
    ["Xiao Ming"."Xiao Ming"."Xiao Ming"."Little red"."Little red"."Little red"],
    ["Chinese"."Mathematics"."English"."Chinese"."Mathematics"."English",]
]

fig = go.Figure()

fig.add_bar(x=x,
            y=[91.72.83.104.85.66],
            name="Last term"
           )
fig.add_bar(x=x,
            y=[106.85.64.93.72.81],
            name="Next semester"
           )

fig.update_layout(barmode="relative")

fig.show()
Copy the code

Horizontal bar graph based on PX

Base bar chart

Two points to note:

  • Data on the X and y axes needs to be exchanged
  • Add parametersorientation
df1 = pd.DataFrame({
    "name": ["Xiao Ming"."Little red"."Zhou Ming"."Red"."Zhang"]."age": [20.28.18.25.36]."score": ["150"."170"."160"."168"."154"]
})

df1
Copy the code

fig = px.bar(
    df1,
    y="name".# xy-axis data needs to be exchanged!!
    x="age",
    orientation='h'   # Settings: Change to horizontal bar chart
)
fig.show()
Copy the code

Display data information

fig = px.bar(
    df1,
    y="name",   
    x="age",
    orientation='h'.# Horizontal bar chart
    text="age"   # Data to display
)
fig.show()
Copy the code

The default text is displayed internally and can be modified:

# Change the text position

fig = px.bar(
    df1,
    y="name".The # xy axis data needs to be swapped
    x="age",
    orientation='h'.# Horizontal bar chart
    text="age"   # Data to display
)

fig.update_traces(textposition="outside")  # ['inside', 'outside', 'auto', 'none']

fig.show()
Copy the code

Setting color Parameters

fig = px.bar(
    df1,
    y="name",   
    x="age",
    color="age".# color parameter
    orientation='h'.# Horizontal bar chart
    text="age"   
)

fig.update_traces(textposition="outside")  # ['inside', 'outside', 'auto', 'none']

fig.show()
Copy the code

Custom colors

fig = px.bar(
    df1,
    y="name",   
    x="age",
    color_discrete_sequence=px.colors.diverging.RdBu,  # Custom colors
    orientation='h'.# Horizontal bar chart
    text="age"   
)

fig.update_traces(textposition="outside")  # ['inside', 'outside', 'auto', 'none']

fig.show()
Copy the code

Tips case

Multi-parameter personality setting

fig = px.bar(
    tips, 
    x="total_bill", 
    y="sex", 
    color='day', 
    orientation='h',
    hover_data=["tip"."size"],
    height=400,
    title='Tip case')
fig.show()
Copy the code

Horizontal bar graph based on GO

Basic shapes

fig = go.Figure(go.Bar(
            x=df1["score"].tolist(),  # X-axis data
            y=df1["name"].tolist(),  # Y-axis data
            orientation='h'))

fig.show()
Copy the code

Set the color and mode

import plotly.graph_objects as go

# generate canvas
fig = go.Figure()

# Add 3 graphics tracks
fig.add_trace(go.Bar(
    y=['Ming'.'little red'.'Joe'],
    x=[120.74.103],
    name='Chinese',
    orientation='h',
    marker=dict(
        color='rgba (246, 78, 139, 0.6)',
        line=dict(color='rgba (246, 78, 139, 1.0)', width=3)
    )
))

fig.add_trace(go.Bar(
    y=['Ming'.'little red'.'Joe'],
    x=[92.128.89],
    name='mathematics',
    orientation='h',
    marker=dict(
        color='rgba (5, 71, 80, 0.6)',
        line=dict(color='rgba (58, 71, 80, 1.0)', width=3)
    )
))

fig.add_trace(go.Bar(
    y=['Ming'.'little red'.'Joe'],
    x=[92.78.69],
    name='English',
    orientation='h',
    marker=dict(
        color='rgba (18, 7, 80, 0.6)',
        line=dict(color='rgba (58, 71, 80, 1.0)', width=3)
    )
))


fig.update_layout(barmode='stack')  [' overlay', 'group', 'overlay', 'relative']


fig.show()
Copy the code

Comparison of 4 different modes:

conclusion

Plotly_express and Plotly. Graph_objects are two ways to implement bar charts and horizontal bar charts with different requirements and display modes. This article introduces how to implement bar charts and horizontal bar charts with different requirements and display modes based on plotly_express and Plotly.