繁体   English   中英

如何使用 matplotlib 显示 X 轴上所有 365 个不同刻度标签的 xticks?

[英]How to show xticks for all 365 distinct tick labels on the X-axis using matplotlib?

我绘制了两条线图。 对于 Y 轴,因为值的数量较少,所以 Y 轴清晰可见。 但是,对于 X 轴,有 365 个值对应于一年中的 365 天。 对于 X 轴,X 轴值看起来非常混乱。 我创建了一个对应于“月-日”的列表(从 01-01 到 12-31,即 1 月 1 日到 12 月 31 日),这些是xticks 我尝试将 X 轴的刻度标签旋转 45 度和 90 度。 但它进一步扰乱了 X 轴刻度标签。

我正在使用 matplotlib 绘制线图。 有没有办法清楚地显示 X 轴上所有 365 个值的 X 轴刻度标签?
这是 output plot 我得到的刻度标签旋转 90: 在此处输入图像描述

365 个刻度线无法在一个轴上清晰可读。 我建议使用多个 x 轴来显示不同比例的数据。 这将至少提供一些关于发生的事情和时间的信息。

# pip install matplotlib
# pip install pandas
# pip install numpy

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import pandas as pd
import random
from datetime import date

# set test data
start_date = date(2022, 1, 1)
end_date = date(2022, 12, 31)
x1 = np.random.uniform(low=20, high=40, size=(365)).astype(int)
x2 = np.random.uniform(low=-40, high=-20, size=(365)).astype(int)
labels = [date.fromordinal(i) for i in range(start_date.toordinal(), end_date.toordinal()+1)]
df = pd.DataFrame({'labels': labels, 'chart1': x1, 'chart2': x2})

# plot charts
fig, ax1 = plt.subplots(figsize=(20,5))
ax1.plot(df['labels'], df['chart1'], 'r')
ax1.plot(df['labels'], df['chart2'], 'b')
plt.fill_between(labels, x1, x2, alpha=0.10, color='b', interpolate=True)

# set 1st x-axis (DAYS) with interval in 4 days to make xticks values visible
ax1.xaxis.set_major_locator(mdates.DayLocator(interval=4))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d'))
plt.xticks(rotation = 90)

# create a twin Axes sharing the yaxis
ax2, ax3, ax4 = ax1.twiny(), ax1.twiny(), ax1.twiny()

# Set 2nd x-axis (WEEK NUM)
ax2.xaxis.set_major_locator(mdates.WeekdayLocator())
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%U'))
ax2.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_label_position('bottom')
ax2.spines['bottom'].set_position(('outward', 50))
ax2.set_xlim(ax.get_xlim())


# Set 3rd x-axis (MONTH)
ax3.xaxis.set_major_locator(mdates.MonthLocator())
ax3.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
ax3.xaxis.set_ticks_position('bottom')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 100))
ax3.set_xlim(ax.get_xlim())


# Set 4th x-axis (YEAR)
ax4.xaxis.set_major_locator(mdates.YearLocator())
ax4.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax4.xaxis.set_ticks_position('bottom')
ax4.xaxis.set_label_position('bottom')
ax4.spines['bottom'].set_position(('outward', 150))
ax4.set_xlim(ax.get_xlim())


# set labels for x-axes
ax1.set_xlabel('Day')
ax2.set_xlabel('Week num')
ax3.set_xlabel('Month')
ax4.set_xlabel('Year')

plt.show()

退货

在此处输入图像描述

暂无
暂无

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

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