Some operations related to drawing by Python Matplotlib

本文介绍了如何使用Python生成从1958到1991年的时间序列,并演示了如何将x轴的标签格式设置为年份,以及如何限制x轴的最大刻度数量以提高视觉效果,通过旋转刻度标签增强可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Create time

there are some situations that we will meet to create time as x-axis. this code means generate a set of time from 1958 to 1991.

 time =  np.arange('1958', '1991', dtype='datetime64[M]').tolist()

The example of the output of this code is:

[datetime.date(1958, 1, 1), datetime.date(1958, 2, 1), datetime.date(1958, 3, 1), datetime.date(1958, 4, 1), datetime.date(1958, 5, 1), datetime.date(1958, 6, 1), datetime.date(1958, 7, 1), datetime.date(1958, 8, 1), datetime.date(1958, 9, 1), datetime.date(1958, 10, 1), datetime.date(1958, 11, 1), datetime.date(1958, 12, 1), datetime.date(1959, 1, 1), datetime.date(1959, 2, 1), datetime.date(1959, 3, 1), datetime.date(1959, 4, 1), datetime.date(1959, 5, 1), datetime.date(1959, 6, 1), datetime.date(1959, 7, 1), datetime.date(1959, 8, 1), datetime.date(1959, 9, 1), datetime.date(1959, 10, 1), datetime.date(1959, 11, 1), datetime.date(1959, 12, 1), datetime.date(1960, 1, 1), etc]

  1. Rewrite the representation of the x-axis

We have figured out how to generate time for the month, but now we want to display the year on the x-axis.

ax.xaxis.set_major_formatter(mdate.DateFormatter('%Y'))

this code can make it can also we can change the parameter into ‘%Y%M%D’ to show the month or day.

  1. the number of items on the x-axis

however, we will face a large range of time, but we only want show some of them

ax.xaxis.set_major_locator(plt.MaxNLocator(10))  # Show 10 ticks on the x-axis

this code will be help that means only show 10 ticks on the x-axis.
to make it x-axis more visually appealing. we can rotate the ticks like this code.

plt.xticks(rotation=45)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值