0

There are many solutions for plotting dates on the x-axis with matplotlib. A good one I found here (3.Answer) [Plotting dates on the x-axis with Python's matplotlib - Stack Overflow] **How do I get the graph with the x-axis and data displayed in a Tkinter canvas and not in the normal matplot window? **

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

I searched in stackoverflow and in matplotlib examples and documentation. I found many solutions for drawing in canvas with matplotlib and also for drawing an x-axis with dates with matplotlib, but no solution for drawing an x-axis with dates with matplotlib in a tkinter canvas. I assume that this is not complicated. Nevertheless, I could not find a solution until now.

weki
  • 1
  • 1

1 Answers1

0

In the meantime I was able to create an example myself and solve my problem. Maybe it helps others.

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

The result diagram

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
weki
  • 1
  • 1