我如何绘制一个图表,其中每个月的值都显示在 x 标签中,只显示年份?在 Matplotlib.Pyplot 中

问题描述 投票:0回答:1
    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()

这是我的代码

它访问数据库检索付款月份和年份的值,您可以在下图中看到结果。

我希望不是在 xlabel 中显示所有月份,而是每年有一个显示年份,还有两条垂直线显示该年结束和下一年开始的时间,但保持图表的每月粒度

python matplotlib plot psycopg2
1个回答
0
投票

尝试一下,看看是否有效。不确定这是否正是您所需要的,但也许它可以帮助您:

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



© www.soinside.com 2019 - 2024. All rights reserved.