matplotlib: Controlling pie chart font color, line width

元气小坏坏 提交于 2019-12-03 23:58:30

问题


I'm using some simple matplotlib functions to draw a pie chart:

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

However, I couldn't find out how to set a default font color, line color, font size – or pass them to pie(). How is it done?


回答1:


Global default colors, line widths, sizes etc, can be adjusted with the rcParams dictionary:

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

A complete list of params can be found here.

You could also adjust the line width after you draw your pie chart:

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.

Unfortunately, I can not figure out a way to adjust the font color or size of the pie chart labels from the pie method or the Wedge object. Looking in the source of axes.py (lines 4606 on matplotlib 99.1) they are created using the Axes.text method. This method can take a color and size argument but this is not currently used. Without editing the source, your only option may be to do it globally as described above.




回答2:


Showing up a bit late for the party but I encountered this problem and didn't want to alter my rcParams.

You can resize the text for labels or auto-percents by keeping the text returned from creating your pie chart and modifying them appropriately using matplotlib.font_manager.

You can read more about using the matplotlib.font_manager here: http://matplotlib.sourceforge.net/api/font_manager_api.html

Built in font sizes are listed in the api; "size: Either an relative value of ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’ or an absolute font size, e.g. 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()




回答3:


matplotlib.rcParams['font.size'] = 24

does change the pie chart labels font size



来源:https://stackoverflow.com/questions/1915871/matplotlib-controlling-pie-chart-font-color-line-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!