将 Matplotlib 饼图百分比标签覆盖为总和不为 100% 的特定值

Override Matplotlib pie chart percentage labels to a specific value that doesn't sum to 100%

我有一个由以下代码给出的饼图

import matplotlib.pyplot as plt

colorPalette=["#61412B","#DCC57D","#D57838","#FFCE33"]

fig, (ax1,ax2)=plt.subplots(1,2,figsize=(10,10))
labels=["Small","Mid","Large"]
values=[.258,.284,.458]
ax1.pie(values,labels=labels,explode=[0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')
labels=["Market Peg","Primary Peg (Passive)","Limit","MidPoint Peg"]
values=[.027,.09,.35,.534]
ax2.pie(values,labels=labels,explode=[0.01,0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')

我注意到我在第二个图上的输入值 53.4% 被推到了 53.3%。有没有办法覆盖它并仍然显示 53.4,即使它加起来超过 100%?

您实际上可以将标签重新定义为您想要的任何内容:

import matplotlib.pyplot as plt

colorPalette=["#61412B","#DCC57D","#D57838","#FFCE33"]

fig, (ax1,ax2)=plt.subplots(1,2,figsize=(10,10))
labels=["Small","Mid","Large"]
values=[.258,.284,.458]
ax1.pie(values,labels=labels,explode=[0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')
labels=["Market Peg","Primary Peg (Passive)","Limit","MidPoint Peg"]
values=[.027,.09,.35,.534]
l = ax2.pie(values,labels=labels,explode=[0.01,0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')

# get the Text object and change the text
l[2][-1].set_text('95.3%')

输出:

工作原理

pie returns 包含图形的一些元素的列表:楔形、外部标签和内部标签(我们想要的)。

>>> l
([<matplotlib.patches.Wedge at 0x7f709a12e130>,
  <matplotlib.patches.Wedge at 0x7f709a12e850>,
  <matplotlib.patches.Wedge at 0x7f709a12eee0>,
  <matplotlib.patches.Wedge at 0x7f709a13a5b0>],
 [Text(1.1060171651625381, 0.09394695506413589, 'Market Peg'),
  Text(0.9985589871945, 0.4847473043690852, 'Primary Peg (Passive)'),
  Text(-0.2875697258635596, 1.0721024450894407, 'Limit'),
  Text(-0.11648807636083792, -1.1038707026032315, 'MidPoint Peg')],
 [Text(0.6078112349091426, 0.051628506837047644, '2.7%'),
  Text(0.5487576416113918, 0.2663926627613891, '9.0%'),
  Text(-0.1580338133124066, 0.5891734157698728, '35.0%'),
  Text(-0.064015969891992, -0.6066316473765505, '53.4%')])

作为一个好的做法,饼图数字总和应达到 100%。饼图旨在显示整体的部分,因此任何低于或高于 100% 的总和都不能代表整个图片。

实际上,您可以通过在 autopct 中传递一个函数来在百分比旁边添加实际值。这样就不需要去修改百分比了。

如果你真的想改变百分比,你可以通过改变pct

来修改create_autopct函数来做同样的事情
import matplotlib.pyplot as plt

def autopct(values):
def create_autopct(pct):
    total = sum(values)
    val = pct*total/100.0
    # pct = 50.0  -> calculate and update your value
    # return f'{pct:.1f}%)'
    return f'{pct:.1f}%  ({val:g})'
return create_autopct

colorPalette=["#61412B","#DCC57D","#D57838","#FFCE33"]

fig, (ax1,ax2)=plt.subplots(1,2,figsize=(10,10))
labels=["Small","Mid","Large"]
values=[.258,.284,.458]
ax1.pie(values,labels=labels,explode=[0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')
labels=["Market Peg","Primary Peg (Passive)","Limit","MidPoint Peg"]
values=[.027,.09,.35,.534]
ax2.pie(values,labels=labels,explode=[0.01,0.01,0.01,0.01],colors=colorPalette,autopct=autopct(values))

output chart