【问题标题】:How to make MxN piechart plots with one legend and removed y-axis titles in Matplotlib如何使用一个图例制作 MxN 饼图并在 Matplotlib 中删除 y 轴标题
【发布时间】:2015-12-03 11:18:32
【问题描述】:

我有以下代码:

import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
np.random.seed(123456)
import pandas as pd
df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], columns=['x', 'y','z','w'])

f, axes = plt.subplots(1,4, figsize=(10,5))
for ax, col in zip(axes, df.columns):
    df[col].plot(kind='pie', autopct='%.2f', ax=ax, title=col, fontsize=10)
    ax.legend(loc=3)
    plt.ylabel("")
    plt.xlabel("")

plt.show()

这使得下面的情节:

我怎样才能做到以下几点:

  • M=2 x N=2 绘图,M 和 N 的值可以改变。
  • 移除 y 标题轴
  • 删除图例
  • 将其保存到文件中

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    具有共享图例的多个饼图

    在我看来,在这种情况下,使用 matplotlib 手动绘制事物比使用 pandas 数据框绘图方法更容易。这样你就有更多的控制权。绘制完所有饼图后,您可以仅在第一个轴上添加图例:

    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(123456)
    import pandas as pd
    
    df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                      columns=['x', 'y','z','w'])
    
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    
    fig, axes = plt.subplots(1,4, figsize=(10,5))
    for ax, col in zip(axes, df.columns):
        ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
        ax.set(ylabel='', title=col, aspect='equal')
    
    axes[0].legend(bbox_to_anchor=(0, 0.5))
    
    fig.savefig('your_file.png') # Or whichever format you'd like
    plt.show()
    

    改用pandas 绘图方法

    但是,如果您更喜欢使用绘图方法:

    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(123456)
    import pandas as pd
    
    df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                      columns=['x', 'y','z','w'])
    
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    
    fig, axes = plt.subplots(1,4, figsize=(10,5))
    for ax, col in zip(axes, df.columns):
        df[col].plot(kind='pie', legend=False, ax=ax, autopct='%0.2f', title=col,
                     colors=colors)
        ax.set(ylabel='', aspect='equal')
    
    axes[0].legend(bbox_to_anchor=(0, 0.5))
    
    fig.savefig('your_file.png')
    plt.show()
    

    两者产生相同的结果。


    重新排列子图网格

    如果您想要 2x2 或其他网格排列的绘图,plt.subplots 将返回一个二维轴数组。因此,您需要直接迭代 axes.flat 而不是 axes

    例如:

    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(123456)
    import pandas as pd
    
    df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                      columns=['x', 'y','z','w'])
    
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    
    fig, axes = plt.subplots(nrows=2, ncols=2)
    for ax, col in zip(axes.flat, df.columns):
        ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
        ax.set(ylabel='', title=col, aspect='equal')
    
    axes[0, 0].legend(bbox_to_anchor=(0, 0.5))
    
    fig.savefig('your_file.png') # Or whichever format you'd like
    plt.show()
    

    其他网格排列

    如果您希望网格排列的轴数多于您拥有的数据量,则需要隐藏您未在其上绘制的所有轴。例如:

    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(123456)
    import pandas as pd
    
    df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'], 
                      columns=['x', 'y','z','w'])
    
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    
    fig, axes = plt.subplots(nrows=2, ncols=3)
    for ax in axes.flat:
        ax.axis('off')
    
    for ax, col in zip(axes.flat, df.columns):
        ax.pie(df[col], labels=df.index, autopct='%.2f', colors=colors)
        ax.set(ylabel='', title=col, aspect='equal')
    
    axes[0, 0].legend(bbox_to_anchor=(0, 0.5))
    
    fig.savefig('your_file.png') # Or whichever format you'd like
    plt.show()
    


    省略标签

    如果您不希望标签环绕在外面,请省略 pielabels 参数。但是,当我们这样做时,我们需要通过为艺术家传递艺术家和标签来手动构建图例。这也是演示使用fig.legend 将单个图例相对于图形对齐的好时机。我们将把图例放在中心,在这种情况下:

    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(123456)
    import pandas as pd
    
    df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                      columns=['x', 'y','z','w'])
    
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    
    fig, axes = plt.subplots(nrows=2, ncols=2)
    for ax, col in zip(axes.flat, df.columns):
        artists = ax.pie(df[col], autopct='%.2f', colors=colors)
        ax.set(ylabel='', title=col, aspect='equal')
    
    fig.legend(artists[0], df.index, loc='center')
    
    plt.show()
    

    将百分比标签移到外面

    同样,百分比标签的径向位置由pctdistance kwarg 控制。大于 1 的值会将百分比标签移出饼图。但是,百分比标签(居中)的默认文本对齐方式假定它们在饼图中。将它们移出饼图后,我们将需要使用不同的对齐约定。

    import matplotlib.pyplot as plt
    import numpy as np
    np.random.seed(123456)
    import pandas as pd
    
    def align_labels(labels):
        for text in labels:
            x, y = text.get_position()
            h_align = 'left' if x > 0 else 'right'
            v_align = 'bottom' if y > 0 else 'top'
            text.set(ha=h_align, va=v_align)
    
    df = pd.DataFrame(3 * np.random.rand(4, 4), index=['a', 'b', 'c', 'd'],
                      columns=['x', 'y','z','w'])
    
    plt.style.use('ggplot')
    colors = plt.rcParams['axes.color_cycle']
    
    fig, axes = plt.subplots(nrows=2, ncols=2)
    for ax, col in zip(axes.flat, df.columns):
        artists = ax.pie(df[col], autopct='%.2f', pctdistance=1.05, colors=colors)
        ax.set(ylabel='', title=col, aspect='equal')
        align_labels(artists[-1])
    
    fig.legend(artists[0], df.index, loc='center')
    
    plt.show()
    

    【讨论】:

    • 谢谢,但我也喜欢控制绘图矩阵,例如 M=2xN=2 绘图或 3x1 绘图。
    • 我尝试修改为fig, axes = plt.subplots(2,2, figsize=(10,5)),但不起作用。
    • @neversaint - 在这种情况下,您需要遍历axes.flat,因为axes 将是一个二维数组。
    • 你的意思是你的第二个例子?我试过了,但传说已经消失了。你能举个例子吗?
    • @neversaint - 我已经更新了答案以显示这两个示例。抱歉耽搁了。工作妨碍了:)
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2019-02-15
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多