如何解决matplotlib在Wedge补丁中保留长宽比饼图
我想在特定位置绘制彩色饼图,而不会扭曲其圆形纵横比。我正在使用Wedge补丁,因为找不到更好的解决方案。这是代码
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patches,collections
fig,axes = plt.subplots()
for i in range(20):
x = np.random.uniform(low=0,high=1,size=10).cumsum()
axes.scatter(x=x,y=np.repeat(i,x.shape[0]),c='gray',s=1)
pies = []
N = 4
cmap = plt.cm.get_cmap("hsv",N + 1)
colors = list(map(cmap,range(N)))
print(colors)
for i in range(2,2 + N):
thetas = np.linspace(0,360,num=i)
assert len(thetas) - 1 <= len(colors)
for theta1,theta2,c in zip(thetas[:-1],thetas[1:],colors):
wedge = patches.Wedge((i,i),r=i / 10,theta1=theta1,theta2=theta2,color=c)
pies.append(wedge)
axes.add_collection(collections.PatchCollection(pies,match_original=True))
plt.show()
如何保持饼图的长宽比?不能选择设置axes.set_aspect("equal")
,因为当我有更多数据点时,它会完全挤压绘图。
我一直在查看how to draw circles and preserve the aspect ratio,但此处无法采用该解决方案-我绘制的是楔形/饼图,而不是圆形。
我也看了matplotlib transforms,但那里也找不到答案。
解决方法
我尝试了同样的方法,matplotlib 并没有试图让您轻松完成这项工作,但我找到了一个您应该可以使用的解决方案。
您需要将中心与楔形分开,并将它们作为偏移添加到 PatchCollection 中。然后你可以对偏移量(transOffset)和形状(transform)应用不同的变换。
请注意,我更改了 r 值(半径)。该值不再位于数据坐标中,因此无论缩放多少,它都应始终保持相同的大小,但它太小而无法在 i/10
处看到。
from matplotlib import patches,collections,transforms
offsets = []
for i in range(2,2 + N):
thetas = np.linspace(0,360,num=i)
assert len(thetas) - 1 <= len(colors)
for theta1,theta2,c in zip(thetas[:-1],thetas[1:],colors):
wedge = patches.Wedge((0,0),r=10,theta1=theta1,theta2=theta2,color=c)
offsets.append((i,i))
pies.append(wedge)
coll = collections.PatchCollection(
pies,match_original=True,offsets=offsets,transform=transforms.IdentityTransform(),transOffset=axes.transData
)
,
当我设置set_aspect('equal')
时,它对我来说很好:
由于y范围比x范围长,因此图像变窄。
如果将y_lim设置在0到小于y_max的数字之间,则会发现效果更好:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patches,collections
fig,axes = plt.subplots()
for i in range(20):
x = np.random.uniform(low=0,high=1,size=10).cumsum()
axes.scatter(x=x,y=np.repeat(i,x.shape[0]),c='gray',s=1)
pies = []
N = 4
cmap = plt.cm.get_cmap("hsv",N + 1)
colors = list(map(cmap,range(N)))
print(colors)
for i in range(2,colors):
wedge = patches.Wedge((i,i),r=i / 10,color=c)
pies.append(wedge)
axes.add_collection(collections.PatchCollection(pies,match_original=True))
axes.set_aspect('equal')
axes.set_ylim(0,7.5)
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。