【问题标题】:Matplotlib and plt.connectMatplotlib 和 plt.connect
【发布时间】:2020-07-02 09:41:34
【问题描述】:

早安

我已经做了一个条形图,我希望通过鼠标事件改变图表栏中的位置。我是新手,无法让它工作,我把代码放在下面。

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

np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000,200000,3650), 
                   np.random.normal(43000,100000,3650), 
                   np.random.normal(43500,140000,3650), 
                   np.random.normal(48000,70000,3650)], 
                  index=[1992,1993,1994,1995])


df['mean']=df.mean(axis=1)
df['std']=df.std(axis=1)
fig, ax = plt.subplots()
years = df.index.values.tolist()
averages = df['mean'].values.tolist()
stds =df['std'].values.tolist()
x_pos = np.arange(len(years))
min_value = int(df.values.min())
max_value =int(df.values.max())
yaxis = np.arange(min_value,max_value, 100)
plt.bar(x_pos,averages, color='red')
ax.set_xticks(x_pos)
ax.set_xticklabels(years)
ax.set_ylabel('Values')
ax.set_title('Average values per year')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
line = ax.axhline(y=10000,color='black')
traza=[]

def onclick(event):
    if not event.inaxes:
            return
    traza.append('onclick '+event.ydata())
    line.set_data([0,1], event.ydata())

plt.connect('button_press_event', onclick)


plt.show()

我什至无法完成 onclick 过程。你能帮帮我吗?

谢谢

【问题讨论】:

    标签: python matplotlib mouseevent


    【解决方案1】:

    有几件事情出错了:

    • event.ydata 不是函数,因此不能将其称为event.ydata()。直接使用即可。
    • 当某些图形信息发生变化时,屏幕上的图像不会立即更新(因为可能会有很多变化,连续重绘可能会很慢)。完成所有更改后,调用fig.canvas.draw() 将更新屏幕。
    • 'onclick ' + event.ydata 不起作用。 'onclick' 是一个字符串,ydata 是一个数字。要连接字符串和数字,首先将数字转换为字符串:'onclick ' + str(event.ydata)
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    def onclick(event):
        if not event.inaxes:
            return
        line.set_data([0, 1], event.ydata)
        fig.canvas.draw()
    
    np.random.seed(12345)
    df = pd.DataFrame([np.random.normal(32000, 200000, 3650),
                       np.random.normal(43000, 100000, 3650),
                       np.random.normal(43500, 140000, 3650),
                       np.random.normal(48000, 70000, 3650)],
                      index=[1992, 1993, 1994, 1995])
    
    df['mean'] = df.mean(axis=1)
    df['std'] = df.std(axis=1)
    fig, ax = plt.subplots()
    years = df.index.values.tolist()
    averages = df['mean'].values.tolist()
    stds = df['std'].values.tolist()
    x_pos = np.arange(len(years))
    min_value = int(df.values.min())
    max_value = int(df.values.max())
    yaxis = np.arange(min_value, max_value, 100)
    plt.bar(x_pos, averages, color='red')
    ax.set_xticks(x_pos)
    ax.set_xticklabels(years)
    ax.set_ylabel('Values')
    ax.set_title('Average values per year')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    line = ax.axhline(y=10000, color='black', linestyle=':')
    
    plt.connect('button_press_event', onclick)
    plt.show()
    

    【讨论】:

    • 非常感谢您的回答。我已经按照您的建议进行了更改。但我认为由于某种原因,onclick 过程永远不会执行。事实上,如果确实如此,我会看到你指出的一些错误。
    • 这取决于您的环境。如果你在 jupyter notebook 中运行,你可能需要%matplotlib notebook(不是%matplotlib inline,它显示没有交互性的图,参见例如this post)。或者您可以在 PyCharm 等交互式环境中运行。
    • 谢谢您,我发现您的上一条评论有问题。
    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多