[PYTHON] [Visualization] I want to draw a beautiful graph with Plotly

this is

Plotly can draw beautiful graphs with a small amount of code, but since I used only matplotlib and did not know much, it is a memorandum of the person who tried to get started while checking.

environment

Google colaboratory

Installation

If it is colab, there is no installation, but if you need it, you can install it with pip

pip install plotly

Data preparation

I have time series data that can be used immediately with seaborn, so I will use it. The following is data preparation, so skip it

import seaborn as sns
import pandas as pd
from calendar import month_name

month_name_mappings = {name[:3]: n for n, name in enumerate(month_name)}

#Just data preparation
df = sns.load_dataset('flights')
df["month"] = df.month.apply(lambda x: month_name_mappings[x])
df["year-month"] = pd.to_datetime(df.year.astype(str) + "-" + df.month.astype(str))
ts_data = df[["passengers", "year-month"]].set_index("year-month")["passengers"]
ts_data
year-month
1949-01-01    112
1949-02-01    118
1949-03-01    132
1949-04-01    129
1949-05-01    121
             ... 
1960-08-01    606
1960-09-01    508
1960-10-01    461
1960-11-01    390
1960-12-01    432
Name: passengers, Length: 144, dtype: int64

Simple data on the number of passengers per month.

basic operation

I will create a graph

import plotly.graph_objects as go

fig = go.Figure()
fig.show()

image.png

Now you have a graph.

#Line graph
fig = go.Figure()
fig.add_trace(go.Scatter(x=ts_data.index, y=ts_data.values, name="passengers"))
fig.show()

image.png

Try to display the memory in logarithm

#Line graph
fig = go.Figure()
fig.add_trace(go.Scatter(x=ts_data.index, y=ts_data.values, name="passengers"))

#To customize the appearance, play with layout
fig.update_layout(yaxis_type="log")
fig.show()

image.png

I want to draw a gorgeous graph

I want to make it more luxurious, so I will try to visualize it in various ways.

--Split the data by month and make a line graph of the changes in each data --Try to make a bar graph of the total number of passengers for each year

#Knead the data a little
ts_data_monthly = df.groupby("month")["passengers"].apply(list)
ts_sum_yearly = df.groupby("year")["passengers"].sum()
#I want to make multiple line graphs
ts_data_monthly
month
1     [112, 115, 145, 171, 196, 204, 242, 284, 315, ...
2     [118, 126, 150, 180, 196, 188, 233, 277, 301, ...
3     [132, 141, 178, 193, 236, 235, 267, 317, 356, ...
4     [129, 135, 163, 181, 235, 227, 269, 313, 348, ...
5     [121, 125, 172, 183, 229, 234, 270, 318, 355, ...
6     [135, 149, 178, 218, 243, 264, 315, 374, 422, ...
7     [148, 170, 199, 230, 264, 302, 364, 413, 465, ...
8     [148, 170, 199, 242, 272, 293, 347, 405, 467, ...
9     [136, 158, 184, 209, 237, 259, 312, 355, 404, ...
10    [119, 133, 162, 191, 211, 229, 274, 306, 347, ...
11    [104, 114, 146, 172, 180, 203, 237, 271, 305, ...
12    [118, 140, 166, 194, 201, 229, 278, 306, 336, ...
Name: passengers, dtype: object
#I want to make a bar graph
ts_sum_yearly
year
1949    1520
1950    1676
1951    2042
1952    2364
1953    2700
1954    2867
1955    3408
1956    3939
1957    4421
1958    4572
1959    5140
1960    5714
Name: passengers, dtype: int64
#label(x axis)
ts_labels = ts_sum_yearly.index
ts_labels
Int64Index([1949, 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959,
            1960],
           dtype='int64', name='year')

Let's visualize it. I played with the layout a little.

fig = go.Figure()

#Make a line graph for monthly time series data
for month, passengers in ts_data_monthly.iteritems():
    fig.add_trace(go.Scatter(x=ts_labels, y=passengers, name=str(month)+"Month", yaxis='y2'))

#Make a bar graph for the yearly total
fig.add_trace(go.Bar(x=ts_labels, y=ts_sum_yearly.values, name="total", yaxis="y1"))

#To customize the appearance, play with layout
#Since there are two axes, there is no memory
fig.update_layout(
    title={
        "text": "Passenger number time series data",
        "x":0.5,
        "y": 0.9
    },
    legend={
        "orientation":"h",
        "x":0.5,
        "xanchor":"center"
    },
    yaxis1={
        "title": "Number of passengers(total)",
        "side": "left",
        "showgrid":False
    },
    yaxis2={
        "title": "Number of passengers(By month)",
        "side": "right",
        "overlaying": "y",
        "showgrid":False
    }
)
fig.show()

image.png

You can flutter the legend. It's amazing to be able to draw a graph that can be moved a little with such a small amount of code ...

Other

Donuts (cute)

import numpy as np

ts_sum_monthly = df.groupby("month")["passengers"].sum()
#Make it look like a moon-cut pizza with the most passengers
pull=[0]*12
pull[np.argmax(ts_sum_monthly.values)] = 0.2

fig = go.Figure()
fig.add_trace(go.Pie(
    labels=[str(month) + "Month" for month in ts_sum_monthly.index],
    values=ts_sum_monthly.values,
    hole=.3,
    pull=pull
    )
)
fig.update_layout(
    title={
        "text": "Percentage of passengers(1949~1960 total)",
        "x":0.5,
        "y": 0.9
    }
)
fig.show()

image.png

Create a pie chart for the total number of passengers each year

from plotly.subplots import make_subplots

specs = [[{'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}] for _ in range(3)]
# 3*Divide the graph into 4 grids
fig = make_subplots(rows=3, cols=4, specs=specs)

#The position of the label title in each pie chart of the label
pos_x = [0.09, 0.37, 0.63, 0.91]
pos_y = [0.9, 0.5, 0.1]
annotations = []  

# (row, col)Place a pie chart at the position of
row = 0
for i, (year, df_yearly) in enumerate(df.groupby(["year"])[["month","passengers"]]):
    pull=[0]*12
    pull[np.argmax(df_yearly.passengers.values)] = 0.2
    col = i%4+1
    if col == 1:
        row += 1
    annotations.append({
        "text": str(year)+"Year",
        "x": pos_x[col-1],
        "y": pos_y[row-1],
        "font_size": 10,
        "showarrow":False
    })
    fig.add_trace(go.Pie(
        labels=[str(month) + "Month" for month in df_yearly.month.values],
        values=df_yearly.passengers.values,
        name=str(year)+"Year",
        hole=.3,
        pull=pull
    ),
    row, col
    )

fig.update_layout(
    title={
        "text": "Percentage of passengers(Yearly)",
        "x":0.5,
        "y": 0.9
    },
    annotations=annotations
)
fig.show()

image.png

the end

Am I the only one who is happy that the graphs work? Next time I would like to summarize a web framework called dash that allows you to create dashboards with plotly.

The site that I used as a reference

Recommended Posts

[Visualization] I want to draw a beautiful graph with Plotly
(Matplotlib) I want to draw a graph with a size specified in pixels
How to draw a 2-axis graph with pyplot
I want to make a game with Python
I want to write to a file with Python
Draw a graph with NetworkX
Draw a graph with networkx
[Python] How to draw a line graph with Matplotlib
I want to transition with a button in flask
I tried to draw a route map with Python
I want to work with a robot in python.
I want to split a character string with hiragana
I want to run a quantum computer with Python
I want to bind a local variable with lambda
Draw a graph with Julia + PyQtGraph (2)
I want to make a blog editor with django admin
I want to start a jupyter environment with one command
Draw a loose graph with matplotlib
I want to make a click macro with pyautogui (desire)
Draw a graph with Julia + PyQtGraph (1)
Draw a graph with Julia + PyQtGraph (3)
I want to make a click macro with pyautogui (outlook)
I want to use a virtual environment with jupyter notebook!
Draw a graph with pandas + XlsxWriter
I want to do ○○ with Pandas
Make a nice graph with plotly
I want to debug with Python
Draw a graph with PySimple GUI
Data visualization with Python-It's too convenient to draw a graph by attribute with "Facet" at once
I want to use a wildcard that I want to shell with Python remove
I want to do a full text search with elasticsearch + python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I want to detect objects with OpenCV
I want to print in a comprehension
How to draw a graph using Matplotlib
I want to blog with Jupyter Notebook
I want to build a Python environment
I want to pip install with PythonAnywhere
I want to analyze logs with Python
I want to play with aws with python
Draw a graph with PyQtGraph Part 1-Drawing
I want to create a graph with wavy lines omitted in the middle with matplotlib (I want to manipulate the impression)
I tried using "Asciichart Py" which can draw a beautiful graph on the console with Python.
I tried to draw a system configuration diagram with Diagrams on Docker
I want to make matplotlib a dark theme
Draw a flat surface with a matplotlib 3d graph
I want to easily create a Noise Model
Draw a graph with Japanese labels in Jupyter
I want to use MATLAB feval with python
I want to analyze songs with Spotify API 2
I want to INSERT a DataFrame into MSSQL
How to draw a 3D graph before optimization
A memo that made a graph animated with plotly
I want to create a window in Python
Draw a graph by processing with Pandas groupby
[Python] Draw a directed graph with Dash Cytoscape
I want to mock datetime.datetime.now () even with pytest!
Try to draw a life curve with python
I want to display multiple images with matplotlib.
I want to knock 100 data sciences with Colaboratory
I want to be an OREMO with setParam!