如何在Matplotlib中使用一个图例和已删除的y轴标题制作MxN饼图

永不圣徒

我有以下代码:

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标题轴
  • 删除图例
  • 保存到文件
乔·金顿

具有共享图例的多个饼图

我认为,在这种情况下,手动绘制事物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()

两者产生相同的结果。


重新布置子图网格

If you'd like to have a 2x2 or other grid arrangement of plots, plt.subplots will return a 2D array of axes. Therefore, you'd need to iterate over axes.flat instead of axes directly.

For example:

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()

在此处输入图片说明

Other Grid Arrangements

If you'd like a grid arrangement that has more axes than the amount of data you have, you'll need to hide any axes that you don't plot on. For example:

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()

在此处输入图片说明


Omitting Labels

If you don't want the labels around the outside, omit the labels argument to pie. However, when we do this, we'll need to build up the legend manually by passing in artists and labels for the artists. This is also a good time to demonstrate using fig.legend to align the single legend relative to the figure. We'll place the legend in the center, in this case:

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()

在此处输入图片说明

Moving Percentage Labels Outside

类似地,百分比标签的径向位置由pctdistancekwarg控制大于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()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在matplotlib中使用2个不同的y轴时,如何制作平方图?

如何使用matplotlib为多个子图制作一个图例?

如何使用matplotlib为多个子图制作一个图例?

如何在其中一个图上使用共享 X 轴和多个 Y 轴的堆叠图?

如何在matplotlib中使用Latex在轴标题中获得一个千分号?

在R中使用mfrow:如何为每个子图赋予不同的y标签和x轴一个标签

Matplotlib图:删除轴,图例和空白

如何在多面板中删除饼图中的间距,并使用r在顶部仅显示一个图例

如何使用 Matplotlib 制作逐行饼图?

在matplotlib中使用.subplot时如何添加标题,x轴标签和y轴标签?

创建一个没有轴但带有标题和 y 标签的子图

当使用ggplot覆盖另一个图时,如何制作自定义图例?

Matplotlib:如何在2个独立的轴上显示条形图和折线图例?

如何在 Matplotlib 中折叠饼图上方和轴标题下方的空间?

单击使用 plotly 和 rshiny 包制作的饼图区域时,我想获取一个列表

使用 matplotlib 显示多个 y 轴脊时减少一个子图的宽度

如何在一个matplotlib轴中集成子图?

Cowplot程序包:如何在R中使用plot_grid()将多个图安排成一个图后,如何垂直向下对齐图例

如何在 matplotlib 中使用不同的 xlimit 和 x 轴的大小绘制子图?

Matplotlib:如何绘制两个具有相同x / y轴但一个沿y轴从另一个开始的条形图

Highcharts:如何在第一个标记旁边放置Y轴标题?

Highcharts半饼-删除饼图和图例之间的空间

使用matplotlib在同一图中使用不同的y轴绘制条形图和线图(无熊猫)

Matplotlib:如何绘制一个x值的一维数组,其中y轴与热图相对应?

如何在Python matplotlib中使用分类变量更改x和y轴刻度?

如何在R中使用`ggdraw`和`plot_grid()`在一系列绘图中在X和Y轴上创建通用标题?

使用不同大小的 y 轴制作相同的 matplotlib 图

如何在 R 中使用图例成功制作轮廓增强的漏斗图?

如何在 Python 中使用 matplotlib 将第二个子图置于第一个子图之上?