Visualize the artifact plot to draw a tree view

Hello, I'm Peter~

Today, I bring you an article about Plotly drawing: how to use Plotly to draw a rectangular tree view

Plotly article

At present, Plotly's article has been updated to Article 17. Several articles are recommended:

gossip

Why does Peter keep writing Plotly's articles? Before the national day, a reader added Peter's VX:

1. Your tutorial on Plotly is very helpful to me 🦀

2. Undergraduate junior began to roll 😭

3. Yamako University, excellent 👍

There was another Plotly reader who also read Peter's article:

So let's study hard together and Peter will write articles well. Maybe one day you will benefit from reading them~

What is a tree graph

tree diagram is a method to show the structural properties of hierarchical structure in the form of images. It is mainly expressed through the relationship between father and son. For example, China Guangdong Shenzhen is an example. The relationship between China and Guangdong and between Guangdong and Shenzhen is a manifestation of this relationship.

The following is a classic graph about the hierarchical structure of tree graph found on the Internet:

Let's take another look at a modern tree with great impact:

This shape is called cushion tree. It uses texture to make each rectangle look "convex" like a cushion in the middle and gradually thin to the edge. This visual effect takes advantage of human's interpretation of this type of shadow as a convex surface, so that different rectangles can be recognized more quickly

Reference resources:

1. Plotly official website: https://plotly.com/python/treemaps/

2. Tree maps in rectangular form - data visualization of complex hierarchies: https://www.idesigntools.com/treemaps.html

Import library

The tree diagram introduced in this article will still use plot_ Express and plot.graph_ Objects can be drawn in two ways. The following is the forerunner entry:

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  # Draw subgraph

Based on plot_ Express drawing

2.1 foundation tree view

When drawing the tree graph, it is based on the list form of data

name = ["China","Fujian", "Guangdong","Xiamen","Shenzhen", "Zhuhai", "Hubei", "Hunan", "Changsha", "Shaanxi","city in Hunan","Xianyang","Dongguan"]
parent = ["", "China", "China","Fujian", "Guangdong", "Guangdong", "China", "China", "Hunan", "China","Hunan","Shaanxi","Guangdong"]


fig = px.treemap(
    names = name,
    parents = parent)
fig.update_traces(root_color="lightgrey")

fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))

fig.show()

2.2 tree diagram based on DataFrame

The above data is in our customized list form. Generally, in pandas, the data will be in the format of DataFrame. How to draw a tree?

Here, we use the self-contained consumption data set in plot:

fig = px.treemap(
    df,  # incoming data 
    path=[px.Constant("all"),"day","sex","time"],  # Key: transfer data path
    values="tip"  # The value shows which field to use
)

fig.update_traces(root_color="lightskyblue") 

fig.update_layout(margin=dict(t=30,l=20,r=25,b=30))   

fig.show()

You can also set color parameters:

fig = px.treemap(
    df,
    path=[px.Constant("all"),"day","sex","time"],  # Key: transfer data path
    values="tip",
    color="time"   # Specifies the parameters for the color change
)

fig.update_traces(root_color="lightskyblue")

fig.update_layout(margin=dict(t=30,l=20,r=25,b=30))   

fig.show()

2.3 tree with continuous color change

gdp data set is adopted here:

fig = px.treemap(
    df1,
    path=[px.Constant("world"),"continent","country"], # route
    values="pop",  # value
    color="lifeExp",  # Value of color
    hover_data=["iso_alpha"],  # Hover data
    color_continuous_scale="RdBu",  # Color change settings
    color_continuous_midpoint=np.average(df1["lifeExp"],
                                        weights=df1["pop"])
)

fig.update_layout(margin = dict(t=40, l=15, r=35, b=45))

fig.show()

2.4 tree view based on discrete color change

Consumption based data sets are also used:

The drawing code is as follows:

fig = px.treemap(
    df,   # incoming data 
    path=[px.Constant("all"), 'sex', 'day', 'time'],   # Data path
    values='total_bill',   # Adopted value
    color='time',   # colour
    color_discrete_map={'(?)':'lightgrey',   # Discrete color settings
                        'Lunch':'gold', 
                        'Dinner':'darkblue'})

fig.update_layout(margin = dict(t=50, l=15, r=25, b=35))

fig.show()

3 drawing based on go.Treemap

3.1 foundation tree view

 name = ["China","Fujian", "Guangdong","Xiamen","Shenzhen", "Zhuhai", "Hubei", "Hunan", "Changsha", "Shaanxi","city in Hunan","Xianyang","Dongguan"]
parent = ["", "China", "China","Fujian", "Guangdong", "Guangdong", "China", "China", "Hunan", "China","Hunan","Shaanxi","Guangdong"]


fig = go.Figure(go.Treemap(  # go method implementation
    labels = name,
    parents = parent,
    root_color = "lightgrey"
))

fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))

fig.show()

3.2 tree diagram of different colors

There are many ways to set the color of the tree view

1. Mode 1

name = ["China","Fujian", "Guangdong","Xiamen","Shenzhen", "Zhuhai", "Hubei", "Hunan", "Changsha", "Shaanxi","city in Hunan","Xianyang","Dongguan"]
parent = ["", "China", "China","Fujian", "Guangdong", "Guangdong", "China", "China", "Hunan", "China","Hunan","Shaanxi","Guangdong"]
color = ["pink", "royalblue", "lightgray", "purple", "cyan", "lightgray", "lightblue", "lightgreen"]


fig = go.Figure(go.Treemap(  
    labels = name,
    parents = parent,
    marker_colors = color   # Method 1: marker_colors parameter settings
))

fig.update_layout(margin = dict(t=50, l=25, r=25, b=25))

fig.show()

Mode 2:

name = ["China","Fujian", "Guangdong","Xiamen","Shenzhen", "Zhuhai", "Hubei", "Hunan", "Changsha", "Shaanxi","city in Hunan","Xianyang","Dongguan"]
parent = ["", "China", "China","Fujian", "Guangdong", "Guangdong", "China", "China", "Hunan", "China","Hunan","Shaanxi","Guangdong"]

fig = go.Figure(go.Treemap(  
    labels = name,
    parents = parent,
))

fig.update_layout(
    margin = dict(t=50, l=25, r=25, b=25),
    # Method 2: set the treemapcolorway parameter
    treemapcolorway = ["pink","blue","red","lightblue","purple","royalblue"])

fig.show()

Mode 3:

name = ["China","Fujian", "Guangdong","Xiamen","Shenzhen", "Zhuhai", "Hubei", "Hunan", "Changsha", "Shaanxi","city in Hunan","Xianyang","Dongguan"]
parent = ["", "China", "China","Fujian", "Guangdong", "Guangdong", "China", "China", "Hunan", "China","Hunan","Shaanxi","Guangdong"]
values = [0,10,20,30,44,55,60,70,88,96,127,150,180]


fig = go.Figure(go.Treemap(  
    labels = name,
    parents = parent,
    values = values,
    marker_colorscale = 'Blues'  # Mode 3
))

fig.update_layout(
    margin = dict(t=20, l=25, r=25, b=25))

fig.show()

If we want to control the size of all label contents to be the same, we can use the uniformtext parameter to control.

Here we use an online CSV file:

fig = go.Figure(go.Treemap(
    ids = df2.ids, 
    labels = df2.labels,  # label
    parents = df2.parents,  # Parent path
    pathbar_textfont_size = 20,  # Font size of the path
    root_color = "lightblue"  # Color under root
))

fig.update_layout(uniformtext=dict(minsize=10,mode="hide"),
                  margin=dict(t=50,l=25,r=25,b=25))

fig.show()

Tags: Python Visualization

Posted on Thu, 14 Oct 2021 17:53:05 -0400 by AceOfJames