【发布时间】:2021-06-21 22:50:08
【问题描述】:
我正在尝试创建一个带有文本下方的图表,但我无法弄清楚为什么文本框 bins_text 没有显示。这是代码示例:
from matplotlib import pyplot as plt
from matplotlib.widgets import Button
results = [1,3,3,5]
class Index:
def __init__(self):
self.ind = 10
self.draw_new_hist()
def next(self, event):
self.ind += 1
self.remove_prev_hist()
self.draw_new_hist()
def prev(self, event):
if self.ind > 1 : self.ind -= 1
self.remove_prev_hist()
self.draw_new_hist()
def draw_new_hist(self):
count, bins, self.bars = ax.hist(results, bins = self.ind, alpha = 0.5, color = "blue", ec = "black")
ax.set_xlim([0.99*min(bins),1.01*max(bins)])
ax.set_ylim([0,1.1*max(count)])
self.bins_text = plt.text(-7,2,"number of bins : " + str(self.ind))
plt.draw()
def remove_prev_hist(self) :
t = [b.remove() for b in self.bars]
self.bins_text.remove()
fig, ax = plt.subplots()
plt.subplots_adjust(left = 0.1, bottom = 0.3)
callback = Index()
Box_button_1 = plt.axes([0.7, 0.05, 0.1, 0.075])
Box_button_2 = plt.axes([0.81, 0.05, 0.1, 0.075])
Button_prev = Button(ax = Box_button_1, label = 'Previous')
Button_prev.on_clicked(callback.prev)
Button_next = Button(ax = Box_button_2, label = 'Next')
Button_next.on_clicked(callback.next)
plt.show()
我尝试更改坐标但没有结果,所以我认为问题是别的,有人可以帮我吗?
编辑:
用第一个代码示例更改坐标就足够了,在这里它不起作用。问题是,在我点击任何按钮之前,文本框没有显示,但是在我点击其中一个之后重新运行相同的代码(因为我再次调用self.draw_new_hist())文本“神奇地”出现了,但我不知道为什么。
【问题讨论】:
标签: python python-3.x matplotlib text