簡體   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