Python - 如何隐藏标签并保留图例 matplotlib?

Posted

技术标签:

【中文标题】Python - 如何隐藏标签并保留图例 matplotlib?【英文标题】:Python - How to hide labels and keep legends matplotlib? 【发布时间】:2017-01-15 00:02:41 【问题描述】:

我想删除饼图的标签并仅保留图例。目前,我的代码两者都有。知道如何删除标签吗?

我试过下面的代码:

plt.legend(labels, loc="best") 

and 

labels=None 

Bu 没用。

我的完整代码是:

plt.pie(percent,              # data
    explode=explode,    # offset parameters 
    labels=country,      # slice labels
    colors=colors,      # array of colours
    autopct='%1.0f%%',  # print the values inside the wedges - add % to the values 
    shadow=True,        # enable shadow
    startangle=70       # starting angle
    )

plt.axis('equal')
plt.title('Top 5 Countries', y=1.05, fontsize=15) #distance from plot and size
plt.legend( loc="best") 
plt.tight_layout()

countrypie = "%s_country_pie.png" % pname
plt.savefig(countrypie)

感谢您的意见

【问题讨论】:

【参考方案1】:

如果您将代码更改为以下内容,则应删除标签并保留图例:

plt.pie(percent,              # data
    explode=explode,    # offset parameters 
    labels=None,      # OR omit this argument altogether
    colors=colors,      # array of colours
    autopct='%1.0f%%',  # print the values inside the wedges - add % to the values 
    shadow=True,        # enable shadow
    startangle=70       # starting angle
)

plt.axis('equal')
plt.title('Top 5 Countries', y=1.05, fontsize=15) #distance from plot and size
plt.legend( loc="best", labels=country) 
plt.tight_layout()

countrypie = "%s_country_pie.png" % pname
plt.savefig(countrypie)

【讨论】:

【参考方案2】:

如果我正确理解您的问题,这应该可以解决。 从饼图创建中删除标签并将标签添加到图例 -

plt.pie(percent,              # data
    explode=explode,    # offset parameters 
    colors=colors,      # array of colours
    autopct='%1.0f%%',  # print the values inside the wedges - add % to the values 
    shadow=True,        # enable shadow
    startangle=70       # starting angle
    )

plt.axis('equal')
plt.title('Top 5 Countries', y=1.05, fontsize=15) #distance from plot and size
plt.legend(loc="best", labels=country) 
plt.tight_layout()

countrypie = "%s_country_pie.png" % pname
plt.savefig(countrypie)

【讨论】:

谢谢,但实际上您的建议 labels=country 没有用。仍然可见的标签和图例。 这对你有用吗(没有标签,图例存在) - ` import matplotlib.pyplot as plt # 切片将按逆时针方向排列和绘制。标签 = 'Frogs', 'Hogs', 'Dogs', 'Logs' 尺寸 = [15, 30, 45, 10] 颜色 = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'] explode = ( 0, 0.1, 0, 0) # 只“分解”第二个切片(即“Hogs”) plt.pie(sizes, explode=explode, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90) plt.legend( loc="best", labels=labels) plt.show() ` 我发现如果我在对plt.pie 的调用中省略labels 参数或设置labels=None,然后调用plt.legend(loc="best",labels=country),我可以只实现一个图例而没有标签。这不适合你吗? @TomRon 这个例子给了我图例和标签..就像我的代码一样,或者像你建议的那样添加标签=国家。安格斯 - 它有效。谢谢! 好的 - 我会发布作为答案!

以上是关于Python - 如何隐藏标签并保留图例 matplotlib?的主要内容,如果未能解决你的问题,请参考以下文章

Python matplotlib图例如何减少框架左边缘和标记之间的距离

如何在python中隐藏刻度标签但保持刻度不变?

如何在 plotly (Python) 中解决此图例标签问题?

取消隐藏后如何保留堆栈视图子项的约束?

在python中将带有数值的图例格式化为标签

隐藏刻度标签值但保留轴标签