matplotlib:控制饼图字体颜色、线宽

问题描述 投票:0回答:4

我正在使用一些简单的 matplotlib 函数来绘制饼图:

f = figure(...)
pie(fracs, explode=explode, ...)

但是,我找不到如何设置默认字体颜色、线条颜色、字体大小——或将它们传递给 pie()。它是怎么做到的?

matplotlib font-size
4个回答
15
投票

聚会有点晚了,但我遇到了这个问题,不想改变我的 rcParams。

您可以通过保留创建饼图返回的文本并使用 matplotlib.font_manager 适当修改它们来调整标签或自动百分比的文本大小。

您可以在此处阅读有关使用 matplotlib.font_manager 的更多信息: http://matplotlib.sourceforge.net/api/font_manager_api.html

内置字体大小在api中列出; “大小:'xx-small'、'x-small'、'small'、'medium'、'large'、'x-large'、'xx-large' 的相对值或绝对字体大小,例如12"

from matplotlib import pyplot as plt
from matplotlib import font_manager as fm

fig = plt.figure(1, figsize=(6,6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
plt.title('Raining Hogs and Dogs')

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]

patches, texts, autotexts = ax.pie(fracs, labels=labels, autopct='%1.1f%%')

proptease = fm.FontProperties()
proptease.set_size('xx-small')
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)

plt.show()

alt text


13
投票

全局默认颜色、线宽、大小等,可以使用 rcParams 字典进行调整:

import matplotlib
matplotlib.rcParams['text.color'] = 'r'
matplotlib.rcParams['lines.linewidth'] = 2

可以在这里找到完整的参数列表。

您还可以在绘制饼图后调整线宽:

from matplotlib import pyplot as plt
fig = plt.figure(figsize=(8,8))
pieWedgesCollection = plt.pie([10,20,50,20],labels=("one","two","three","four"),colors=("b","g","r","y"))[0] #returns a list of matplotlib.patches.Wedge objects
pieWedgesCollection[0].set_lw(4) #adjust the line width of the first one.

不幸的是,我无法从 pie 方法或 Wedge 对象中找出调整字体颜色或饼图标签大小的方法。查看 axes.py 的源代码(matplotlib 99.1 上的第 4606 行),它们是使用 Axes.text 方法创建的。此方法可以采用颜色和大小参数,但当前未使用。在不编辑源代码的情况下,您唯一的选择可能是如上所述在全局范围内进行。


3
投票
matplotlib.rcParams['font.size'] = 24

确实改变了饼图标签的字体大小


0
投票

要在饼图中指定线宽和颜色,请在 pie() 中添加:wedgeprops={'linewidth': 2.0, 'edgecolor': 'white'}:

plt.pie([10,20,50,20],labels=("one","two","three","four"),colors=("b","g","r","y"), wedgeprops={'linewidth': 2.0, 'edgecolor': 'white'})

© www.soinside.com 2019 - 2024. All rights reserved.