python - 从子图元素中获取已打印标签的列表,以避免图例中的重复输入

标签 python python-3.x matplotlib legend subplot

考虑Python中的这个函数:

def plots(fields, dev_data, plot_dict, width, color='b', offset=0, l=""):
    ii = 0
    for f in fields:
        ind = np.arange(len(dev_data[ii])) # the x locations for the groups
        import pdb
        plot_dict[f][1].bar(ind + offset, dev_data[ii], width, color=color, label=l, bottom=0)
        if (len(f)>1): #this is used to create a bottom ex. 
            plot_dict[f][1].bar(ind + offset, dev_data[ii+1], width, color='c', label= "free Memory", bottom=dev_data[ii])
            ii += 1
        ii += 1

它获取输入数据列表 (dev_data) 并将它们绘制为条形图。 fields 是包含数据信息的元组列表。通常每个元组都有一个元素,但如果有 2 个元素,则意味着来自 dev_data 的 2 个后续数据必须绘制在另一个之上。

该函数在每次运行时传递的子图上绘制数据。问题如下:如果我使用相同的 plt.subfigures 列表调用 plots 两次,它将执行这部分:

           if (len(f)>1): #this is used to create a bottom ex. 
                plot_dict[f][1].bar(ind + offset, dev_data[ii+1], width, color='c', label= "free Memory", bottom=dev_data[ii])
                ii += 1

两次绘制具有相同值的标签两次,如图所示。

为了避免这种行为,我想获取图中所有现有的标签,这样如果已经存在,我就不会将 label 参数传递给 bar 方法,例如:

if (len(f)>1): #this is used to create a bottom ex. 
    if "free Memory" not in plot_dict[f][1].get_existing_labels():
        plot_dict[f][1].bar(ind + offset, dev_data[ii+1], width, color='c', label= "free Memory", bottom=dev_data[ii])
    else:
        plot_dict[f][1].bar(ind + offset, dev_data[ii+1], width, color='c', bottom=dev_data[ii])
    ii += 1

做一些类似于 get_existing_labels 的事情,对于 matplotlib Axes 类来说是存在的,返回例如 ['[0]', '[1]', '可用内存']。 ?

希望我的问题很清楚。 这是一个最小的完整且可验证的示例:

import matplotlib.pyplot as plt
import numpy as np
def plots(fields, dev_data, plot_dict, width, color='b', offset=0, l=""):
    ii = 0
    for f in fields:
        ind = np.arange(len(dev_data[ii])) # the x locations for the groups
        import pdb
        plot_dict[f][1].bar(ind + offset, dev_data[ii], width, color=color, label=l, bottom=0)
        if (len(f)>1): #this is used to create a bottom ex. (RAM_used, RAM_free)
            plot_dict[f][1].bar(ind + offset, dev_data[ii+1], width, color='c', label= "free Memory", bottom=dev_data[ii])
            ii += 1
        ii += 1

fields = [('avg_latency',), ('Successful requests',), ('CPU',), ('RAM', 'free RAM')]
dev_data  = [[8.583309839300817, 171.69371585480965, 1094.40896667813, 189.20147247618982], [100.0, 100.0, 100.0, 100.0], [4.8860107086666815, 35.27584414319996, 76.51036722223547, 41.620512010866655], [1416.4132789999996, 1498.8874527999992, 1825.9473847058837, 3796.161298666671], [4585.911099999997, 4399.862112000003, 3348.1968705882373, 521.1009743727773]]
dev_data2  = [[8.583309839300817, 171.69371585480965, 1094.40896667813, 189.20147247618982], [100.0, 100.0, 100.0, 100.0], [4.8860107086666815, 35.27584414319996, 76.51036722223547, 41.620512010866655], [1416.4132789999996, 1498.8874527999992, 1825.9473847058837, 3796.161298666671], [4585.911099999997, 4399.862112000003, 3348.1968705882373, 521.1009743727773]]

d = list()
d.append(dev_data)
d.append(dev_data2)

colors = ['y','b','r','g','y','c']
plot_d = dict(zip(fields,[ plt.subplots()for l in fields]))
width =0.2
l = ['a','b']
for ii, el in enumerate(d):
    plots(fields, d[ii], plot_d, width, colors[ii], width*(ii-1), [ii])
plt.legend()
plt.show()

legend element shown twice

最佳答案

确实存在这样的函数来获取图例和句柄。它被称为 get_legend_handles_labels() 并应用于当前轴。这将返回图例句柄和标签。第一个元素(索引 [0])引用句柄,第二个元素(索引 [1])引用标签。

<小时/>

具体来说,使用以下代码行

import numpy as np
def plots(fields, dev_data, plot_dict, width, color='b', offset=0, l=""):
    ii = 0
    for f in fields:
        ind = np.arange(len(dev_data[ii])) # the x locations for the groups
        import pdb
        plot_dict[f][1].bar(ind + offset, dev_data[ii], width, color=color, label=l, bottom=0)
        if (len(f)>1): #this is used to create a bottom ex. 
            if "free Memory" not in plot_dict[f][1].get_legend_handles_labels()[1]:
                plot_dict[f][1].bar(ind + offset, dev_data[ii+1], width, color='c', label= "free Memory", bottom=dev_data[ii])
            else:
                plot_dict[f][1].bar(ind + offset, dev_data[ii+1], width, color='c', bottom=dev_data[ii])
            ii += 1
        ii += 1

enter image description here

关于python - 从子图元素中获取已打印标签的列表,以避免图例中的重复输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54184751/

相关文章:

python - Mercurial 预提交 Hook : How to hook to python program in current directory?

python - 增加 Tornado 中 BaseIOStream 的 max_buffer_size 限制

基于引用计数以 "wrong"顺序调用的 Python 析构函数

Python3中将列表内容相互相乘的Pythonic方式

python - 正确,Matplotlib 中的 "full length"左右箭头?

python - 字典中元素的配对组合,不重复

python - 如何使用截止或重叠标签调整填充

python - 如何根据列中的值合并列中的值

python - 如何在 Python 中绘制和显示图表

python - matplotlib 中绘图点的标签