python - Matplotlib 使中心圆透明

标签 python matplotlib plot png geometry

我正在绘制饼图,使 png 图像中的背景看起来透明。我怎样才能使中心圆看起来也透明而不是白色? enter image description here

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Correct', 'Wrong'
sizes = [20, 80]

fig1, ax1 = plt.subplots()
ax1.pie(sizes,colors=['green','red'], labels=labels,autopct='%1.1f%%', 
shadow=True, startangle=90)
centre_circle = plt.Circle((0,0),0.75,edgecolor='black', 
facecolor='white',fill=True,linewidth=0.25)
fig1 = plt.gcf()
fig1.gca().add_artist(centre_circle)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
fig1.savefig('foo.png', transparent=True)

最佳答案

在上面的代码中创建白色中间部分的方法是用一个圆圈模糊饼图的中心。这当然不能产生透明的内部。

这个问题的解决方案也可以在更复杂的问题 Double donut chart in matplotlib 中找到.让我详细介绍一下:

为了制作中间有孔的真正圆环图,需要切割楔形,使它们成为部分环。幸运的是,matplotlib 提供了这样做的工具。饼图由几个楔形组成。 来自 matplotlib.patches.Wedge我们学习的文档

class matplotlib.patches.Wedge(center, r, theta1, theta2, width=None, **kwargs)
Wedge shaped patch. [...] If width is given, then a partial wedge is drawn from inner radius r - width to outer radius r.

为了设置所有楔形的宽度,一个简单的方法是使用 plt.setp

wedges, _ = ax.pie([20,80], ...)
plt.setp( wedges, width=0.25)

完整示例:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
fig.set_facecolor("#fff9c9") # set yellow background color to see effect

wedges, text, autotext = ax.pie([25, 40], colors=['limegreen','crimson'],
                                labels=['Correct', 'Wrong'], autopct='%1.1f%%')
plt.setp( wedges, width=0.25)

ax.set_aspect("equal")
# the produced png will have a transparent background
plt.savefig(__file__+".png", transparent=True)
plt.show()

enter image description here


如果 Wedge 没有 width 参数,以下是解决问题的方法。 由于饼图以 (0,0) 为中心,复制外部路径坐标,还原它们并乘以某个小于 1 的数字(在下面的代码中称为 r 用于半径), 给出了内环的坐标。加入这两个坐标列表并注意正确的路径代码可以根据需要创建环形。

import matplotlib.pyplot as plt
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import numpy as np

def cutwedge(wedge, r=0.8):
    path = wedge.get_path()
    verts = path.vertices[:-3]
    codes = path.codes[:-3]
    new_verts = np.vstack((verts , verts[::-1]*r, verts[0,:]))
    new_codes =  np.concatenate((codes , codes[::-1], np.array([79])) )
    new_codes[len(codes)] = 2
    new_path = mpath.Path(new_verts, new_codes)
    new_patch = mpatches.PathPatch(new_path)
    new_patch.update_from(wedge)
    wedge.set_visible(False)
    wedge.axes.add_patch(new_patch)
    return new_patch

fig, ax = plt.subplots()
fig.set_facecolor("#fff9c9") # set yellow background color to see effect


wedges, text, autotext = ax.pie([25, 75], colors=['limegreen','indigo'], 
                                labels=['Correct', 'Wrong'], autopct='%1.1f%%')

for w in wedges:
    cutwedge(w)
    # or try cutwedge(w, r=0.4)

ax.set_aspect("equal")

# the produced png will have a transparent background
plt.savefig(__file__+".png", transparent=True)
plt.show()

enter image description here

关于python - Matplotlib 使中心圆透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45771474/

相关文章:

python - 色调影响颜色以外标记的群图

python - 在 Plotly 中更改标题字体大小

python - 什么是 Python 中的常量?

python - 如何在 Python 中编写带有注释的输入文件

python - 如何使用 matplotlib autopct?

python - 在一行中设置 x 和 y 标签

python - python groupby 图的长度不匹配错误

python - 模块对象不可调用

Python 可以打开文件,PL/Python 不能

python - 为什么我的代码无法绘制有向图的箭头?