Issue
cur.execute( """ SELECT sum(value), Extract ('month' from dateOperation), Extract ('year' from dateOperation) FROM movimenti GROUP BY (Extract ('month' from dateOperation)), (Extract ('year' from dateOperation)) ORDER BY (Extract ('year' from dateOperation)) , (Extract ('month' from dateOperation)) """ )
data = cur.fetchall()
counts, month, year = zip(*data)
plt.plot(list(map(lambda x: f"{int(month[x])}/{int(year[x])}", range(len(month)))), counts, marker='o', color='green',linewidth=3,alpha=0.8,label='Totale')
plt.title('Bilancio annuo:')
plt.xlabel('Data')
plt.ylabel('Valore')
plt.axhline(y=0, color='black', linestyle='--', linewidth=1, label='Zero',alpha=0.5)
plt.grid(True)
plt.legend()
plt.show()
Thats my code
It acces the db retreives the value the month and the year of the payments, you can see the result in the immage below.
I want that instead of all the month being displayed in the xlabels i just have one for each year showing the year and also two vertical lines showing when the year ends and the next one starts, but maintaining the monthly granularity of the graph
Solution
Try this and see if it works. Not sure if it's exactly what you need but maybe it can help:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
counts, months, years = zip(*data)
dates = [datetime(int(y), int(m), 1) for y, m in zip(years, months)]
plt.figure(figsize=(10, 5))
plt.plot(dates, counts, marker='o', color='green', linewidth=3, alpha=0.8, label='Totale')
# Set the locator for x-ticks to the first month of each year
plt.gca().xaxis.set_major_locator(mdates.YearLocator(month=1, day=1))
# Format the x-tick labels to show only the year
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
# Add vertical lines and labels for each year
unique_years = sorted(set(years))
for year in unique_years:
plt.axvline(datetime(int(year), 1, 1), color='red', linestyle='--', linewidth=1, alpha=0.5)
plt.title('Bilancio annuo:')
plt.xlabel('Data')
plt.ylabel('Valore')
plt.axhline(y=0, color='black', linestyle='--', linewidth=1, label='Zero', alpha=0.5)
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.xticks(rotation=45)
plt.show()
Answered By - Federico Wolter
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.