Python库matplotlib之七
- 饼图
- 标注楔形图
- 自动标注楔形图
- 楔形图彩色设置
- 改变楔形图标注和autopct文本位置
饼图
词法:Axes.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, normalize=True, hatch=None, data=None)
绘制饼图。制作数组x的饼图。每个楔形的分数面积由 x/sum(x) 给出。默认情况下,从 x 轴开始,逆时针绘制楔形。
参数说明
- x,该参数类型是一维类数组
- explode,该参数类型是array-like, 默认值为None
- labels,该参数类型是list, 默认值为None
- colors,该参数类型是color,或者类型为color的list, 默认值为None
- hatch,该参数类型是字符串,或list, 默认值为None
- autopct,该参数类型是None,字符串,或者callable, 默认值为None
- pctdistance,该参数类型是float, 默认值为0.6
- labeldistance,该参数类型是float,或者None, 默认值为1.1
- shadow,该参数类型是bool,或者dict, 默认值为False
- startangle,该参数类型是float, 默认值为0度
- radius,该参数类型是float, 默认值为1
- counterclock,该参数类型是bool, 默认值为True
- wedgeprops,该参数类型是dict, 默认值为None
- textprops,该参数类型是dict, 默认值为None
- center,该参数类型是(float, float), 默认值为(0, 0)
- frame,该参数类型是bool, 默认值为False
- rotatelabels,该参数类型是bool, 默认值为False
- normalize,该参数类型是bool, 默认值为True
- data,该参数类型是indexable对象, 是可选的
标注楔形图
绘制饼图,并标记楔形图。要添加标签,将标签列表传递给labels参数
import matplotlib.pyplot as plt
def plot_pie():
fig, ax = plt.subplots()
sizes = [20, 10, 15, 30, 25]
label = ["wheat", "corn", "rice", "patato", "barley"]
l_explode = [0.1, 0.2, 0.3, 0.1, 0.0]
ax.pie(sizes, labels=label, explode=l_explode)
plt.show()
print()
if __name__ == "__main__":
plot_pie()
自动标注楔形图
将函数或格式字符串传递给 autopct 以标记切片。
import matplotlib.pyplot as plt
def plot_pie():
fig, ax = plt.subplots()
sizes = [19.75, 14.25, 15.27, 25.26, 25.47]
label = ["wheat", "corn", "rice", "patato", "barley"]
ax.pie(sizes, labels=label, autopct='%1.2f%%')
plt.show()
print()
if __name__ == "__main__":
plot_pie()
楔形图彩色设置
使用参数colors,设置 楔形图的颜色。
import matplotlib.pyplot as plt
def plot_pie():
fig, ax = plt.subplots()
sizes = [19.75, 14.25, 15.27, 30.47, 20.47]
label = ["wheat", "corn", "rice", "barley", "millet"]
l_color = ["blue","green","#7F007F","magenta", "yellow"]
ax.pie(sizes, labels=label, colors=l_color, autopct='%1.2f%%')
plt.show()
print()
if __name__ == "__main__":
plot_pie()
改变楔形图标注和autopct文本位置
使用参数labeldistance,分别改变改变楔形图标注位置;使用参数rotatelabels,改变楔形图标注的角度。
使用参数pctdistance,改变autopct 文本位置。
import matplotlib.pyplot as plt
def plot_pie():
fig, ax = plt.subplots()
sizes = [19.75, 14.25, 15.27, 30.47, 20.47]
label = ["wheat", "corn", "rice", "barley", "millet"]
l_color = ["blue","green","#7F007F","magenta", "yellow"]
ax.pie(sizes, labels=label, rotatelabels=True, colors=l_color,
autopct='%1.2f%%', pctdistance=1.25, labeldistance=.3)
plt.show()
print()
if __name__ == "__main__":
plot_pie()