Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

i have a python fucntion to plot some data into a tk interface, but my data does not display properly into my graphs, for example

i have a python fucntion to plot some data into a tk interface, but my data does not display properly into my graphs, for example when i select an item, and then it loads all the data, then i select a month such as november but some days for the previous month appear and then not all days for that month appear, i have added my code for the function and also my table from my database that includes some data points not all:
# Create a ttk Notebook for the Table of Contents
toc_notebook = ttk.Notebook(window)
toc_notebook.grid(row=0, column=1, columnspan=20, padx=10, pady=10, sticky='nsew')
# Create frames for each tab
daily_frame = ttk.Frame(toc_notebook)
weekly_frame = ttk.Frame(toc_notebook)
# monthly_frame = ttk.Frame(toc_notebook)
toc_notebook.add(daily_frame, text='Daily Usage')
toc_notebook.add(weekly_frame, text='Weekly Usage')
# toc_notebook.add(monthly_frame, text='Monthly Usage')
# Dropdown for month selection
months =['All Months']+[datetime(2000, m,1).strftime('%B') for m in range(1,13)] # List of months with 'All Months' as the first option
month_var = tk.StringVar(window)
month_combobox = ttk.Combobox(window, textvariable=month_var, values=months, state="readonly")
month_combobox.current(0) # Default to 'All Months'
month_combobox.grid(row=1, column=1, padx=10, pady=5, sticky='w')
toc_frames ={
"Daily Usage": daily_frame,
"Weekly Usage": weekly_frame,
# "Monthly Usage": monthly_frame
}
def draw_graph(item_name, time_period, selected_month = None):
global graph_canvas
if not item_name: # If no item is selected, do nothing
return
# Clear previous graph if it exists
if graph_canvas:
graph_canvas.get_tk_widget().destroy()
# Connect to the database
db = mysql.connector.connect(
host='localhost',
user='root',
password='peter',
database='shop_inventory'
)
cursor = db.cursor()
# Modify the SQL query to filter data based on the selected month
month_condition =""
if selected_month and selected_month != 'All Months':
month_number = datetime.strptime(selected_month, '%B').month
month_condition =" AND MONTH(change_date)=%s"% month_number
if time_period == "Daily Usage":
cursor.execute("""
SELECT DATE(change_date) as date, SUM(quantity_change) as total_change
FROM changes_log
WHERE item_name =%s"""+ month_condition +"""
GROUP BY DATE(change_date)
ORDER BY DATE(change_date) ASC
""",(item_name,))
elif time_period == "Weekly Usage":
cursor.execute("""
SELECT YEARWEEK(change_date) as week, SUM(quantity_change) as total_change
FROM changes_log
WHERE item_name =%s
GROUP BY YEARWEEK(change_date)
ORDER BY YEARWEEK(change_date) ASC
""",(item_name,))
# Fetch the data
data = cursor.fetchall()
dates =[x[0] for x in data]
quantities =[x[1] for x in data]
fig, ax = plt.subplots(figsize=(10,4)) # Adjust the size as needed
ax.plot(dates, quantities, marker='o') # Add markers for each data point
# Adjust the plot margins
plt.subplots_adjust(bottom=0.2) # Increase the bottom margin to allow for more space
# Format the graph based on the time_period
if time_period == "Daily Usage":
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.xaxis.set_major_locator(mdates.DayLocator(interval=1)) # Set interval to show every day
plt.xticks(rotation =90, fontsize =6)
elif time_period == "Weekly Usage":
# Convert week numbers to the starting date of the week for labeling
start_dates =[datetime.strptime(f'{date}-1',"%Y%W-%w") for date in dates]
ax.set_xticks(range(len(start_dates))) # Set x-ticks to be the start dates of weeks
ax.set_xticklabels([date.strftime('%Y-%m-%d') for date in start_dates], rotation=45)
# Embedding the figure in the Tkinter window
graph_canvas = FigureCanvasTkAgg(fig, master=toc_frames[time_period])
graph_canvas.draw()
graph_widget = graph_canvas.get_tk_widget()
graph_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
# Close the database connection
cursor.close()
db.close()
mysql> SELECT *
-> FROM changes_log
-> ORDER BY change_date ASC;
+------+----------------+-------------------+---+-----------------+-----------+
| id | item_name | original_quantity | new_quantity | change_time | emp_id | change_date | quantity_change | rando

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Mobile Communications

Authors: Jochen Schiller

2nd edition

978-0321123817, 321123816, 978-8131724262

More Books

Students also viewed these Programming questions