matplotlib中使用plt.pie画饼图怎么设置labels的颜色和字体?
时间: 2024-02-03 18:11:38 浏览: 20
可以使用plt.pie函数的labels参数来设置饼图中的标签,并使用textprops参数来设置标签的颜色和字体。具体方法如下:
```python
import matplotlib.pyplot as plt
# 设置标签和对应的值
labels = ['A', 'B', 'C', 'D']
values = [30, 20, 40, 10]
# 设置标签的颜色和字体
textprops = {'fontsize': 12, 'color': 'white'}
# 画饼图
plt.pie(values, labels=labels, autopct='%1.1f%%', textprops=textprops)
plt.show()
```
其中,textprops参数是一个字典类型,可以通过字典的方式设置标签的颜色和字体。在示例中,我们设置了字体大小为12,颜色为白色。你也可以根据需要修改字体和颜色的属性。
相关问题
matplotlib中使用plt.pie画饼图怎么设置labels的字体为楷体?
可以使用`fontproperties`参数设置饼图中labels的字体为楷体。
具体代码如下:
```python
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
colors = ['#ff9999','#66b3ff','#99ff99','#ffcc99']
fig1, ax1 = plt.subplots()
ax1.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%',
startangle=90, textprops={'fontproperties': 'Kaiti'})
# 设置饼图中labels的字体为楷体
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()
```
其中`textprops={'fontproperties': 'Kaiti'}`表示设置字体属性为楷体。
import matplotlib.pyplot as plt # 设置饼图的数据和标签 data = [1082, 7367] labels = ['量1', '量2'] # 设置饼图的颜色 colors = ['red', 'green'] # 画饼图 plt.pie(data, labels=labels, colors=colors) # 显示饼图 plt.show()改进代码要求饼图内有百分比
好的,你可以使用 `autopct` 参数来在饼图内显示百分比。以下是修改后的代码:
```python
import matplotlib.pyplot as plt
# 设置饼图的数据和标签
data = [1082, 7367]
labels = ['量1', '量2']
# 设置饼图的颜色
colors = ['red', 'green']
# 画饼图,并在饼图内显示百分比
plt.pie(data, labels=labels, colors=colors, autopct='%1.1f%%')
# 显示饼图
plt.show()
```
在上面的代码中,`autopct='%1.1f%%'` 表示在饼图内显示百分比,其中 `%1.1f` 表示保留一位小数,`%%` 表示输出百分号。你可以根据需要修改保留小数位数或者添加前缀后缀等。