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

Python matplotlib折线图x轴刻度设置:替换日刻度为月份标签

Switching Matplotlib X-Axis to Month Labels (Jan/Feb/etc.)

Hey there! I can help you replace those clunky daily x-axis ticks with clean, readable month labels. Here's a straightforward way to adjust your existing code:

Updated Code with Custom Month Ticks

import matplotlib.pyplot as plt

# Your original data setup
fig = plt.figure()
temp_data = temp_total[:]
# Convert Kelvin to Celsius (your original calculation)
plt.plot(temp_data - 273.15)

# --- Custom month label logic ---
# Define the starting day index for each month (for a 365-day non-leap year)
month_start_indices = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
# List of month abbreviations to display
month_labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

# Replace default x-ticks with our month markers
plt.xticks(ticks=month_start_indices, labels=month_labels, size=10)

# Keep your original axis labels (or tweak the x-label to match the new ticks)
plt.ylabel('Temperature (C)', size=12)
plt.xlabel('Month', size=12)  # Optional: Update to reflect month labels instead of days

# Optional: Add a title and adjust layout to prevent label cutoff
plt.title('Yearly Daily High Temperatures', size=14)
plt.tight_layout()

plt.show()

What's Changed & Why:

  • month_start_indices: This list maps each month to its starting position in your 365-day array. For example, February starts at index 31 (after 31 days of January), March at 59 (31+28 days of February), and so on.
  • plt.xticks(): This is the key function here—it replaces the default daily ticks with our custom positions and month labels. The ticks parameter sets where each label appears, and labels defines the text for each tick.
  • plt.tight_layout(): This ensures your month labels don't get cut off at the edges of the figure, which is a common headache with custom ticks.

If you ever need to handle leap years (366 days), just adjust the month_start_indices to add an extra day after February (so March starts at 60 instead of 59).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:39:04