【问题标题】:Python: plot a graph / distribution of data from total to partsPython:绘制从总体到部分的数据图/分布
【发布时间】:2020-05-27 07:15:05
【问题描述】:

假设我有一些形状为

的数据

其中每一行代表总数(第一行中的 83 个)在某些分组(列)中的分布情况。

有没有办法在 matplotlib 中生成这种图形,或者在 Python 的其他一些库中生成这种图形?最终结果应该是如图所示的一系列图形,水平堆叠

【问题讨论】:

    标签: python plot graph


    【解决方案1】:

    我建议使用networkx python 模块这样做;你可以像这样从pipconda 安装它:

    # pip
    pip install networkx
    
    # conda
    conda install -c anaconda networkx
    

    安装后,您需要使用以下函数,该函数根据您的问题中显示的三个值的列表返回图形及其参数:

    def create_graph(values):
        G = nx.Graph()
        G.add_edges_from([('a','b'),('a','c'), ('a','d')])
        _sum = sum(values)
        labels = {'a': _sum, 'b':values[0], 'c':values[1], 'd':values[2]}
        sizes = [50 * _sum, 50*values[0], 50*values[1], 50*values[2]]
        return G, labels, sizes
    

    现在,让我们看看如何使用这个函数:

    import pandas as pd
    import networkx as nx
    import matplotlib.pyplot as plt
    
    # create dummy data
    df = pd.DataFrame({"A": [2, 42], "B": [41, 1], "C":[40, 27]})
    
    # create subplot based on the number of rows in df
    fig, axes = plt.subplots(nrows=df.shape[0], ncols=1, figsize=(10,10))
    ax = axes.flatten()
    
    # iterate over the rows and draw a graph for each one
    for i, row in df.iterrows():
        graph, labels, sizes = create_graph(row.values)
        nx.draw(graph, node_size=sizes, labels=labels, ax=ax[i])
    
    # show the result
    plt.show()
    

    前面的代码会产生下图:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-25
      • 2015-08-06
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2020-04-17
      • 1970-01-01
      相关资源
      最近更新 更多