You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用plt.plot绘制折线图时的X轴显示问题

Fixing Matplotlib X-Axis to Show Dates Instead of 0-Based Index

Hey there! Let's get that X-axis showing your desired dates (like 2009-03, 2009-04) instead of the default 0-starting indices. The root of your problem is that you're only passing the numeric values of your data to plt.plot()—matplotlib has no idea about your date index right now.

Why Your Current Code Isn't Working

When you use plt.plot(WTS_summary.values), you're only feeding matplotlib the Y-axis values (a numpy array of your data). Since you don't specify an X-axis, it automatically uses a 0-based sequence (0, 1, 2, ...) as the X positions. It never touches the date index stored in WTS_summary at all.

Step-by-Step Fixes

First, make sure your WTS_summary index is actually a datetime type (not just strings). If it's stored as text, convert it first:

import pandas as pd
# Convert index to datetime if it's not already
WTS_summary.index = pd.to_datetime(WTS_summary.index)

Then choose one of these two methods to plot with dates on the X-axis:

Method 1: Use Pandas' Built-in Plot (Easiest)

Pandas integrates seamlessly with matplotlib, and its plot() method automatically uses the DataFrame's index as the X-axis:

import matplotlib.pyplot as plt

plt.figure()
# Plot directly from the DataFrame, specify style, and attach to the current axis
WTS_summary.plot(linewidth=1, alpha=0.7, color='salmon', ax=plt.gca())
plt.xlabel("Date")
plt.ylabel("Y-Axis")
plt.show()

Method 2: Manually Specify X and Y Values

If you prefer to use raw matplotlib, explicitly pass your date index as the X-axis values:

import matplotlib.pyplot as plt

plt.figure()
# Pass the date index as X, and your data values as Y
plt.plot(WTS_summary.index, WTS_summary.values, linewidth=1, alpha=0.7, color='salmon')
plt.xlabel("Date")
plt.ylabel("Y-Axis")
# Optional: Rotate date labels to prevent overlap
plt.xticks(rotation=45)
# Adjust layout so labels don't get cut off
plt.tight_layout()
plt.show()

Bonus Tip

If your dates are still showing up weirdly (like too many or too few), you can use matplotlib's date tick formatter to customize the display:

from matplotlib.dates import DateFormatter

# After plotting
plt.gca().xaxis.set_major_formatter(DateFormatter('%Y-%m'))

内容的提问来源于stack exchange,提问作者Python Rookie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:29:06