python - 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 过程。你可以帮帮我吗?
谢谢
解决方案
有几件事出了问题:
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()
推荐阅读
- ssis - SSIS - 查找重复行并保留具有最高值的行
- php - 如何在laravel中使用ajax上传图片
- python-3.x - 如何从 Python 3 对 Google Datastore 执行基于键的查询?
- swift - NSTouchBar 集成未调用
- ruby-on-rails - 事务隔离级别和锁定记录,对正在运行的事务中的记录禁用 SELECT
- hadoop - 如何使用 FileSystem API 计算分区?
- javascript - 找不到导入 Three.js
- r - 如何从 R 中的子字符串创建数据框?
- sorting - 通过查询反转列数据
- typescript - 如何在 TypeScript 的条件中使用变量来缩小类型?