我正在绘制一个饼图,使png图像中的背景看起来透明。如何使中心圆看起来透明而不是白色?
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)
答案 0 :(得分:3)
在上面的代码中创建白色中间部分的方法是将圆饼的中心混淆圆圈。这当然不能实现透明的内饰。
在更复杂的问题Double donut chart in matplotlib中也可以找到解决方案。让我详细说明一下:
为了制作一个真正的圆环图,中间有一个洞,人们需要切割楔形物,使它们成为部分环。幸运的是,matplotlib提供了这样做的工具。饼图由几个楔子组成。
来自
我们学习的matplotlib.patches.Wedge
文档
class matplotlib.patches.Wedge(center, r, theta1, theta2, width=None, **kwargs)
楔形贴片。 [...]如果给出宽度,则从内半径r - width
到外半径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()
如果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()
答案 1 :(得分:0)
问题在于你并没有真正制作真正的甜甜圈图表。这部分代码
centre_circle = plt.Circle((0,0),0.75,edgecolor='black',
facecolor='white',fill=True,linewidth=0.25)
你在饼图中间画了一个圆圈。问题是如果你使这个圆透明,你将再次看到饼图的中间。我建议使用像pixlr这样的免费照片编辑程序,让它变得透明。除非你能找到一种制作真正的圆环图的方法,否则我不知道该怎么做。
答案 2 :(得分:0)
类似于Double donut chart in matplotlib引用的importanceofbeingearnest解决方案,您将需要使用class A:
val = int()
def __init__(self, val1): #val1 is a string
self.val = val1
def __setattr__(self, name, value):
if isinstance(A.__dict__[name], int):
self.__dict__[name] = int(value)
b = A("4")
print(type(b.val)) #prints <class 'int'>
来设置饼图的宽度,这将使其成为真正的甜甜圈而不是饼图顶部画有实心圆的图表。
plt.setp(pie, width=width)