可视化神器Plotly绘制树状图

大家好,我是Peter~

今天给大家带来的是一篇关于Plotly绘图的文章:如何使用Plotly来绘制矩形树状图

Plotly文章

目前Plotly的文章更新到第17篇,推荐几篇文章:

闲聊

为什么Peter一直坚持写Plotly的文章?国庆节前有位读者加了Peter的VX:

1、你的教程关于Plotly的对我帮助很大🦀

2、本科大三就开始卷了😭

3、山大学子,优秀👍

以前还有另一位Plotly的读者,也是看了Peter的文章:

所以大家一起好好学习,Peter也好好写文章,说不定哪天你看了就会受益~

什么是树图

树状图(tree diagram)是一种将层次结构式的构造性质,以图象方式表现出来的方法。主要是通过父子级的关系来表现的,比如:中国—广东—深圳,就是一个例子。中国和广东之间,广东和深圳之间都是这种关系的表现。

下面是网上找到的一份关于树图的层级结构的图形,很经典:

我们再看一幅现代的很有冲击力的树图:

这种图形叫缓冲垫树状结构图(Cushion Treemap),它使用纹理使每个矩形在中间看起来像垫子一样”凸起”,并且逐渐变细到边缘。这种视觉效果利用了人类将这种类型的阴影解释为凸起的表面的优势,从而可以更快地识别出不同的矩形

参考资源:

1、Plotly官网:https://plotly.com/python/treemaps/

2、矩形式树状结构图(Treemaps)-复杂层次结构的数据可视化:https://www.idesigntools.com/treemaps.html

导入库

本文中介绍的树图还是会使用 plotly_express 和 plotly.graph_objects 两种方法来绘制,下面还是先导入库:

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  # 画子图

基于plotly_express绘制

2.1 基础树状图

在绘制树图的时候是基于数据的列表形式

name = ["中国","福建", "广东","厦门","深圳", "珠海", "湖北", "湖南", "长沙", "陕西","衡阳","咸阳","东莞"]
parent = ["", "中国", "中国","福建", "广东", "广东", "中国", "中国", "湖南", "中国","湖南","陕西","广东"]


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 基于DataFrame的树图

上面的数据是我们自定义的列表形式,一般如果在pandas中,数据会是DataFrame的格式,如何绘制树图呢?

在这里我们使用的plotly中自带的消费数据集:

fig = px.treemap(
    df,  # 传入数据
    path=[px.Constant("all"),"day","sex","time"],  # 重点:传递数据路径
    values="tip"  # 数值显示使用哪个字段
)

fig.update_traces(root_color="lightskyblue") 

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

fig.show()

还可以设置颜色参数:

fig = px.treemap(
    df,
    path=[px.Constant("all"),"day","sex","time"],  # 重点:传递数据路径
    values="tip",
    color="time"   # 指定颜色变化的参数
)

fig.update_traces(root_color="lightskyblue")

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

fig.show()

2.3 带有连续颜色变化的树图

在这里采用的是gdp数据集:

fig = px.treemap(
    df1,
    path=[px.Constant("world"),"continent","country"], # 路径
    values="pop",  # 值
    color="lifeExp",  # 颜色的取值
    hover_data=["iso_alpha"],  # 悬停数据
    color_continuous_scale="RdBu",  # 颜色变化的设置
    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 基于离散颜色变化的树状图

采用的还是基于消费的数据集:

绘图代码如下:

fig = px.treemap(
    df,   # 传入数据
    path=[px.Constant("all"), 'sex', 'day', 'time'],   # 数据路径
    values='total_bill',   # 采用的值
    color='time',   # 颜色
    color_discrete_map={'(?)':'lightgrey',   # 离散型颜色设置
                        'Lunch':'gold', 
                        'Dinner':'darkblue'})

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

fig.show()

3 基于go.Treemap绘制

3.1 基础树状图

 name = ["中国","福建", "广东","厦门","深圳", "珠海", "湖北", "湖南", "长沙", "陕西","衡阳","咸阳","东莞"]
parent = ["", "中国", "中国","福建", "广东", "广东", "中国", "中国", "湖南", "中国","湖南","陕西","广东"]


fig = go.Figure(go.Treemap(  # go方法实现
    labels = name,
    parents = parent,
    root_color = "lightgrey"
))

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

fig.show()

3.2 不同颜色的树图

多种方式来设置树状图的颜色

1、方式1

name = ["中国","福建", "广东","厦门","深圳", "珠海", "湖北", "湖南", "长沙", "陕西","衡阳","咸阳","东莞"]
parent = ["", "中国", "中国","福建", "广东", "广东", "中国", "中国", "湖南", "中国","湖南","陕西","广东"]
color = ["pink", "royalblue", "lightgray", "purple", "cyan", "lightgray", "lightblue", "lightgreen"]


fig = go.Figure(go.Treemap(  
    labels = name,
    parents = parent,
    marker_colors = color   # 方式1:marker_colors参数设置
))

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

fig.show()

方式2:

name = ["中国","福建", "广东","厦门","深圳", "珠海", "湖北", "湖南", "长沙", "陕西","衡阳","咸阳","东莞"]
parent = ["", "中国", "中国","福建", "广东", "广东", "中国", "中国", "湖南", "中国","湖南","陕西","广东"]

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

fig.update_layout(
    margin = dict(t=50, l=25, r=25, b=25),
    # 方式2:通过 treemapcolorway 参数设置
    treemapcolorway = ["pink","blue","red","lightblue","purple","royalblue"])

fig.show()

方式3:

name = ["中国","福建", "广东","厦门","深圳", "珠海", "湖北", "湖南", "长沙", "陕西","衡阳","咸阳","东莞"]
parent = ["", "中国", "中国","福建", "广东", "广东", "中国", "中国", "湖南", "中国","湖南","陕西","广东"]
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'  # 方式3
))

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

fig.show()

如果我们想控制所有的标签内容的大小是相同的,我们可以使用来uniformtext参数来进行控制。

在这里我们采用的是一份在线的CSV文件:

fig = go.Figure(go.Treemap(
    ids = df2.ids, 
    labels = df2.labels,  # 标签
    parents = df2.parents,  # 父级路径
    pathbar_textfont_size = 20,  # 路径的字体大小
    root_color = "lightblue"  # root下的颜色
))

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

fig.show()

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
可以使用Plotly库来绘制具有双坐标轴的形。下面是一个示例代码,展示了如何使用Plotly绘制双坐标轴: ```python import plotly.graph_objects as go # 创建数据 x = [1, 2, 3, 4, 5] y1 = [10, 15, 7, 12, 9] y2 = [50, 30, 40, 20, 25] # 创建第一个坐标轴 fig = go.Figure() fig.add_trace(go.Scatter(x=x, y=y1, name='y1', line=dict(color='blue'))) # 创建第二个坐标轴 fig.add_trace(go.Scatter(x=x, y=y2, name='y2', line=dict(color='red'), yaxis='y2')) # 设置形布局 fig.update_layout( yaxis=dict(title='y1', titlefont=dict(color='blue'), tickfont=dict(color='blue')), yaxis2=dict(title='y2', titlefont=dict(color='red'), tickfont=dict(color='red'), overlaying='y', side='right'), xaxis=dict(title='x') ) # 显示形 fig.show() ``` 在上面的示例代码中,首先创建了x、y1和y2的数据。然后使用`go.Figure()`创建一个新的形对象,使用`add_trace()`方法分别添加两个散点,分别对应y1和y2的数据。在添加第二个散点时,通过`yaxis='y2'`参数指定其使用第二个坐标轴。 接下来,使用`update_layout()`方法设置形的布局。通过`yaxis`参数设置第一个坐标轴的标题和颜色,通过`yaxis2`参数设置第二个坐标轴的标题、颜色、叠加在第一个坐标轴上、并位于右侧。通过`xaxis`参数设置x轴的标题。 最后,使用`fig.show()`显示形。 运行上述代码,将会得到一个带有双坐标轴的形,其中y1使用蓝色线条表示,y2使用红色线条表示。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值