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

如何在Matplotlib中实现X轴不等间距缩放以匹配Excel图表效果

Fixing Uneven X-Axis Scaling in Matplotlib to Match Excel

Got it, let's break down how to get that Excel-style uneven X-axis scaling in Matplotlib. The core issue here is how Matplotlib handles X-values by default vs. how Excel treats them.

Why Your Current Plot Has Equal Spacing

When you run plt.plot(new[201], label='201'), Matplotlib automatically uses sequential integers (0, 1, 2, ...) as the X-axis values—treating your data as a categorical series with equally spaced labels. Excel, on the other hand, will use the actual numerical X-values (if provided) to scale the axis unevenly based on their real magnitude.

How to Adjust the Code

To replicate Excel's behavior, you need to explicitly pass your actual X-axis values to the plot() function. Here's how:

  1. Identify your X-values: First, confirm what the actual X data corresponding to new[201] is. This could be a separate column in your new dataframe, or it might be the index of new[201].

  2. Modify the plot call:

    • If your X-values are in a column (e.g., named x_axis_data):
      plt.plot(new['x_axis_data'], new[201], label='201')
      plt.legend()  # Fixed your typo here (was plt.genend())
      plt.show()
      
    • If the index of new[201] is your X-axis data:
      plt.plot(new[201].index, new[201], label='201')
      plt.legend()
      plt.show()
      

Example to Illustrate

Let's say you have this data:

XY
15
37
63
108
  • Equal spacing (your current output): plt.plot(df['Y']) gives X-axis labels 0,1,2,3 (equally spaced).
  • Uneven spacing (Excel-style): plt.plot(df['X'], df['Y']) plots X-values as 1,3,6,10—with gaps between them matching their numerical difference, just like Excel.

Bonus: Time Series X-Axis

If your X-axis is time-based, convert it to datetime type first, and Matplotlib will automatically handle uneven spacing (e.g., missing days/months):

import pandas as pd
new['datetime_x'] = pd.to_datetime(new['datetime_x'])
plt.plot(new['datetime_x'], new[201], label='201')
plt.legend()
plt.xticks(rotation=45)  # Rotate labels for readability
plt.show()

This will make your Matplotlib plot match the scaling you see in Excel perfectly!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:48:12