使用matplotlib在x轴上绘制日期有许多解决方案。我在这里找到了一个很好的(3.答案([用Python的matplotlib-Stack Overflow在x轴上绘制日期]**如何获得在Tkinter画布中而不是在正常matplot窗口中显示的带有x轴和数据的图形?**
import datetime as dt
dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x))
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()
我在stackoverflow和matplotlib中搜索了示例和文档。我找到了许多使用matplotlib在画布上绘制的解决方案,也找到了使用matplomlib绘制带日期的x轴的解决方案。但没有在tkinter画布中使用matplodlib绘制带时间的x轴。我认为这并不复杂。尽管如此,我直到现在都找不到解决办法。
在此期间,我能够自己创建一个示例并解决我的问题。也许这对其他人有帮助。
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import pandas as pd
from datetime import date
import tkinter as tk
drawInTkinter = True # draw in tkinter canvas or Matplotlib Figure
def weightSeries():
""" returns a series of weights with the corresponding date values """
weight = [83, 86, 84, 82, 77] #list of weights
# list of the assigned date strings in ISO format
dateStr = ['2021-12-25', '2021-12-31', '2022-01-07', '2022-02-01', '2022-03-01']
# list of date objects
dateObj = [date.fromisoformat(d) for d in dateStr]
return pd.Series(weight, index=dateObj)
if drawInTkinter: # draw in tkinter canvas
root=tk.Tk()
fig = mpl.figure.Figure([6,4])
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().pack()
plot1 = fig.add_subplot(1,1,1)
plot1.plot(weightSeries())
canvas.draw()
root.mainloop()
else: # draw in Matplotlib Figure
weightSeries().plot()
plt.show()
结果图