繁体   English   中英

如何控制 x 轴刻度的数量?

[英]How do I control the number of x-axis ticks?

我已经提取了一个我想要使用的数据集,其中包含名为DateAdjusted的列。 调整后的只是基月调整后的百分比增长。

我目前拥有的代码是:

x = data['Date']
y = data['Adjusted']

fig = plt.figure(dpi=128, figsize=(7,3))
plt.plot(x,y)

plt.title("FTSE 100 Growth", fontsize=25)
plt.xlabel("Date", fontsize=14)
plt.ylabel("Adjusted %", fontsize=14)
plt.show()

但是,当我运行它时,我基本上会在底部看到一条实心黑线,所有日期都相互覆盖。 它试图显示每一个日期,而显然我只想显示主要日期。 该日期的格式为 4 月 19 日,数据从 10 月 3 日到 5 月 20 日。

如何将日期刻度和标签的数量限制为每年一个,或我选择的任何数量? 如果您确实有解决方案,如果您可以对代码本身所做的编辑做出回应,那就太好了。 我已经尝试过我在这里找到的其他解决方案,但我无法让它工作。

matplotlibdates模块将完成这项工作。 您可以通过修改MonthLocator来控制间隔(当前设置为 6 个月)。 就是这样:

import pandas as pd
from datetime import date, datetime, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as md
import numpy as np
import matplotlib.ticker as ticker

x = data['Date']
y = data['Adjusted']
#converts differently formatted date to a datetime object
def convert_date(df):
    return datetime.strptime(df['Date'], '%b-%y')
data['Formatted_Date'] = data.apply(convert_date, axis=1)


# plot
fig, ax = plt.subplots(1, 1)
ax.plot(data['Formatted_Date'], y,'ok')

## Set time format and the interval of ticks (every 6 months)
xformatter = md.DateFormatter('%Y-%m') # format as year, month
xlocator = md.MonthLocator(interval = 6)

## Set xtick labels to appear every 6 months
ax.xaxis.set_major_locator(xlocator)

## Format xtick labels as YYYY:mm
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
plt.title("FTSE 100 Growth", fontsize=25)
plt.xlabel("Date", fontsize=14)
plt.ylabel("Adjusted %", fontsize=14)
plt.show()

示例 output:

示例输出

暂无
暂无

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

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