【发布时间】:2021-06-15 21:02:51
【问题描述】:
我正在尝试创建一个可以实时可视化投资组合变化的程序。为此,我更新了我的数据并用它创建了一个新图。当我在 PyCharm 中运行以下代码时,SciView 在 30 次迭代后停止显示图。理想情况下,我希望它只显示最近的情节,但如果它只是截断历史以便我至少总是看到当前情节也可以。有没有办法做到这一点?我尝试了不同的方法来关闭数字(例如使用plt.close()),但没有达到预期的结果。
要重现的代码:
import matplotlib.pyplot as plt
import numpy as np
import random
class RealTimeVisualizer:
def __init__(self, x, y):
self.x = x
self.y = y
def update_data(self, x_value, y_value):
"""
Appends values to the data arrays.
"""
self.x.append(x_value)
self.y.append(y_value)
def create_plot(self):
"""
Takes an x and a y (both 1D arrays and constructs a plot from it)
:return: a pyplot figure object
"""
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# Draw x and y lists
ax.clear()
ax.plot(self.x, self.y)
# Format plot
plt.xticks(rotation=90)
plt.title('Portfolio')
plt.ylabel('Value')
plt.show()
plt.close('all')
if __name__ == '__main__':
portfolio_cash = 10000
tick = 0
real_time_visualizer = RealTimeVisualizer([tick], [portfolio_cash])
for i in np.arange(50):
tick += 1
portfolio_cash += random.randint(-50, 50)
real_time_visualizer.update_data(tick, portfolio_cash)
real_time_visualizer.create_plot()
【问题讨论】:
标签: python matplotlib plot pycharm