如何四舍五入显示在matplotlib饼图中的值?

use*_*ica 1 python charts matplotlib

饼形图的示例代码给出了这里

figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])    
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode=(0, 0.05, 0, 0)

pie(fracs, explode=explode, labels=labels,
                autopct='%1.1f%%', shadow=True, startangle=90)

title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

show()
Run Code Online (Sandbox Code Playgroud)

输出看起来像这样:

饼图演示

我只想说15%,10%等,最后不要有不必要的小数位。我该怎么做呢?

cgo*_*gon 5

只需将autopct ='%1.0 f %%' 更改为autopct = '%1.1 f %%'

"""
Make a pie chart - see
http://matplotlib.sf.net/matplotlib.pylab.html#-pie for the docstring.

This example shows a basic pie chart with labels optional features,
like autolabeling the percentage, offsetting a slice with "explode",
adding a shadow, and changing the starting angle.

"""
from pylab import *

# make a square figure and axes
figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])

# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode=(0, 0.05, 0, 0)

pie(fracs, explode=explode, labels=labels,
                autopct='%1.0f%%', shadow=True, startangle=90)
                # The default startangle is 0, which would start
                # the Frogs slice on the x-axis.  With startangle=90,
                # everything is rotated counter-clockwise by 90 degrees,
                # so the plotting starts on the positive y-axis.

title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

show()
Run Code Online (Sandbox Code Playgroud)