【问题标题】:matplotlib: Controlling pie chart font color, line widthmatplotlib:控制饼图字体颜色、线宽
【发布时间】:2010-12-27 07:35:50
【问题描述】:

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

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

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

【问题讨论】:

    标签: matplotlib font-size


    【解决方案1】:

    参加聚会有点晚了,但我遇到了这个问题,不想改变我的 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()
    

    【讨论】:

    • 效果很好,谢谢。有没有类似的方法来改变切片之间的线宽?
    • 如何根据饼段颜色改变每个标签的字体颜色
    【解决方案2】:
    matplotlib.rcParams['font.size'] = 24
    

    会改变饼图标签的字体大小

    【讨论】:

    • 把它放在你的 plt.pie 声明之上
    【解决方案3】:

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

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

    完整的参数列表可以在here.找到

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

    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 方法创建的。此方法可以采用颜色和大小参数,但当前未使用。在不编辑源代码的情况下,您唯一的选择可能是如上所述在全局范围内进行。

    【讨论】:

    • 谢谢,这很有帮助。一个补充:要设置实际楔形的线宽,您必须使用(对于第一个楔形):pieWedgesCollection[0][0].set_linewidth(0)
    • 那么,如何使“二”绿色、“一”蓝色……的字体颜色?你知道怎么做吗?
    猜你喜欢
    • 2017-11-12
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2019-03-23
    • 1970-01-01
    相关资源
    最近更新 更多