首页 > 解决方案 > Matplotlib 和 plt.connect

问题描述

早上好

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

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 过程。你可以帮帮我吗?

谢谢

标签: pythonmatplotlibmouseevent

解决方案


有几件事出了问题:

  • 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()

推荐阅读