繁体   English   中英

如何使用 Matplotlib 调整图表的 x 轴“日期”标签?

[英]How can I adjust the x-axis "Date" labels of the graph using the Matplotlib?

1.问题
我想知道交易价格随时间的变化,所以我做了一个散点图 plot。 大局画的很粗,小问题没有解决。 就是x轴label的显示区间。我第一次做的结果和部分代码如下。 在此处输入图像描述

import matplotlib.pyplot as plt
import matplotlib
import matplotlib.dates as mdates
from datetime import datetime
import pandas as pd

df = pd.read_excel('data.xlsx')
df = df.loc[df['계약면적(㎡)'] > 33]

# Data in the form of 202109 was made into 2021-09-01 
# and then make date data in the form of 202109 using dt.strftime ('%Y%m').

df['계약년월'] = df['계약년월'].astype(str)
df['계약년월'] = df['계약년월'].str[0:4] + '-' + df['계약년월'].str[4:6] + '-01'

df['계약년월'] = pd.to_datetime(df['계약년월'])
df['계약년월'] = df['계약년월'].dt.strftime('%Y%m')

# Graph

plt.figure(figsize=(30,10))

ax = plt.gca()

yticks = [100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000]
ylabels = [10, 20, 30, 40, 50, 60, 70, 80]
plt.yticks(yticks, labels = ylabels)

ax.xaxis.set_major_locator(mdates.MonthLocator())

plt.scatter(df['계약년월'], df['면적당 금액(원)'])
plt.xlabel('계약년월')
plt.ylabel('면적당 금액(원/㎡)')

plt.savefig('Graph.jpg')

可以看到,xticks的label显示为201101 201308 201512 201807 202101。
我想在每年年底以 20111212 201312 201412 201521 201612 201712 201812 201912 202012 等方式标记这一点。

2.我试过的
由于 yticks 很容易在我的支配下更改,我尝试将相同的方法应用于 xticks。 它的代码如下。

plt.figure(figsize=(30,10))

ax = plt.gca()

yticks = [100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000]
ylabels = [10, 20, 30, 40, 50, 60, 70, 80]
plt.yticks(yticks, labels = ylabels)

# xticks I want to show.
xticks = ['201112', '201212', '201312', '201412', '201512', '201612', '201712', '201812', '201912', '202012']

# For the above list, it was converted into date data in the form of '%Y%m'.

xticks = [datetime.strptime(x, '%Y%m') for x in xticks]

# xlabels displayed in the graph

xlabels = ['2011y-end', '2012y-end', '2013y-end', '2014y-end', '2015y-end', '2016y-end', '2017y-end', '2018y-end', '2019y-end', '2020y-end']

plt.xticks(xticks, labels = xticks)

ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=None, interval=2, tz=None))

plt.scatter(df['계약년월'], df['면적당 금액(원)'])
plt.xlabel('계약년월')
plt.ylabel('면적당 금액(원/㎡)')

plt.savefig('Graph.jpg')

然而,结果却是灾难性的。 在此处输入图像描述 可能是在摸tick的过程中出了问题,这个结果是在201212之后出现的,然后是201213,而不是201301。

我很担心这一点,所以我使用 strftime 和 strptime 将“数据”和“报价列表”都转换为日期形式(“%Y%m”),但我想知道为什么它没有按我的预期应用。

Python 还未使用,是否存在低效代码,敬请谅解,如能解决问题,将不胜感激。

from matplotlib import dates as mdates
plt.xlim(datetime.datetime(2011,12),datetime.datetime(2020,12))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%b\n%Y'))

您可以根据自己的意愿设置 x 轴主要格式,这里我使用%d表示日期, %b表示月份, \n表示换行, %Y表示年份。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM