For循环中用于创建许多交互式绘图的matplotlib(MPL_CONNECT)不起作用

matplotlib(mpl_connect) in for loop to create many interactive plots does not work(For循环中用于创建许多交互式绘图的matplotlib(MPL_CONNECT)不起作用)
本文介绍了For循环中用于创建许多交互式绘图的matplotlib(MPL_CONNECT)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环,它生成不同的数据帧( pandas ),然后绘制它。 我想创建许多交互式绘图,这样我就可以在我的图表中显示和隐藏不同的线。 为此,我使用了On_Pick函数(如前所述here)

问题是,当我绘制一个表时,它可以工作,并且我有交互式图例,但当我尝试在for循环中绘制多个图表时,没有图例是交互式的。

df = pd.DataFrame(np.array([[0.45,0.12,0.66,0.76,0.22],[0.22,0.24,0.12,0.56,0.34],[0.12,0.47,0.93,0.65,0.21]]),
                    columns=[60.1,65.5,67.3,74.2,88.5])
df['name']=['A1','B4','B7']
df=df.set_index('name')

#plot alone:
fig, ax = plt.subplots()
df.T.plot(ax=ax)
lines = ax.get_lines()
leg = ax.legend(fancybox=True, shadow=True)
lined = {}  # Will map legend lines to original lines.
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(True)  # Enable picking on the legend line.
    lined[legline] = origline

def on_pick(event):
    #On the pick event, find the original line corresponding to the legend
    #proxy line, and toggle its visibility.
    legline = event.artist
    origline = lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    #Change the alpha on the line in the legend so we can see what lines
    #have been toggled.
    legline.set_alpha(1.0 if visible else 0.2)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
结果:绘制我可以启用和禁用图例中的线条:

#plot many plots in for loop:
nums=[5,8,0.3]

for n in nums:
    db=df*n
    
    fig, ax = plt.subplots()
    db.T.plot(ax=ax)
    lines = ax.get_lines()
    leg = ax.legend(fancybox=True, shadow=True)
    lined = {}  # Will map legend lines to original lines.
    for legline, origline in zip(leg.get_lines(), lines):
        legline.set_picker(True)  # Enable picking on the legend line.
        lined[legline] = origline
        
    def on_pick(event):
        #On the pick event, find the original line corresponding to the legend
        #proxy line, and toggle its visibility.
        legline = event.artist
        origline = lined[legline]
        visible = not origline.get_visible()
        origline.set_visible(visible)
        #Change the alpha on the line in the legend so we can see what lines
        #have been toggled.
        legline.set_alpha(1.0 if visible else 0.2)
        fig.canvas.draw()
        
    fig.canvas.mpl_connect('pick_event', on_pick)
    plt.show()
    

结果:我得到了曲线图,但不能处理将显示哪些线。

*当我触摸线条时,它仍然交互地显示x和y值,但图例不是交互的。

我的最终目标:在matplotlib中的for循环中生成多个交互式绘图,并能够启用和禁用图例项。

推荐答案

如何同时显示它们,使用fig作为lined的载体

多个独立的地块

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame(np.array([[0.45,0.12,0.66,0.76,0.22],[0.22,0.24,0.12,0.56,0.34],[0.12,0.47,0.93,0.65,0.21]]),
                    columns=[60.1,65.5,67.3,74.2,88.5])
df['name']=['A1','B4','B7']
df=df.set_index('name')

#plot many plots in for loop:
nums=[5,8,0.3]


def on_pick(event):
    #On the pick event, find the original line corresponding to the legend
    #proxy line, and toggle its visibility.
    legline = event.artist
    origline = event.canvas.figure.lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    #Change the alpha on the line in the legend so we can see what lines
    #have been toggled.
    legline.set_alpha(1.0 if visible else 0.2)
    event.canvas.draw()

for n in nums:
    db=df*n
    
    fig, ax = plt.subplots()
    db.T.plot(ax=ax)
    lines = ax.get_lines()
    leg = ax.legend(fancybox=True, shadow=True)
    fig.lined = {}  # Will map legend lines to original lines.
    for legline, origline in zip(leg.get_lines(), lines):
        legline.set_picker(True)  # Enable picking on the legend line.
        fig.lined[legline] = origline
        
        
    fig.canvas.mpl_connect('pick_event', on_pick)

plt.show()

使用子图

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame(np.array([[0.45,0.12,0.66,0.76,0.22],[0.22,0.24,0.12,0.56,0.34],[0.12,0.47,0.93,0.65,0.21]]),
                    columns=[60.1,65.5,67.3,74.2,88.5])
df['name']=['A1','B4','B7']
df=df.set_index('name')

#plot many plots in for loop:
nums=[5,8,0.3]


def on_pick(event):
    #On the pick event, find the original line corresponding to the legend
    #proxy line, and toggle its visibility.
    legline = event.artist
    origline = event.canvas.figure.lined[legline]
    visible = not origline.get_visible()
    origline.set_visible(visible)
    #Change the alpha on the line in the legend so we can see what lines
    #have been toggled.
    legline.set_alpha(1.0 if visible else 0.2)
    event.canvas.draw()

nrows = int(np.ceil(np.sqrt(len(nums))))
ncols = int(np.ceil(len(nums) / nrows))
fig, axs = plt.subplots(nrows=nrows,ncols=ncols)
if not isinstance(axs,np.ndarray):
  axs = np.array([[axs]])
if len(axs.shape)==1:
  axs = np.expand_dims(axs,axis=1)

fig.lined = {}  # Will map legend lines to original lines.
for idx,n in enumerate(nums):
    db=df*n
    
    ax = axs[int(idx/ncols),idx % ncols]
    
    db.T.plot(ax=ax)
    lines = ax.get_lines()
    leg = ax.legend(fancybox=True, shadow=True)
    for legline, origline in zip(leg.get_lines(), lines):
        legline.set_picker(True)  # Enable picking on the legend line.
        fig.lined[legline] = origline
        
        
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

这篇关于For循环中用于创建许多交互式绘图的matplotlib(MPL_CONNECT)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)