如何在Matplotlib中实现X轴不等间距缩放以匹配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:
Identify your X-values: First, confirm what the actual X data corresponding to
new[201]is. This could be a separate column in yournewdataframe, or it might be the index ofnew[201].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()
- If your X-values are in a column (e.g., named
Example to Illustrate
Let's say you have this data:
| X | Y |
|---|---|
| 1 | 5 |
| 3 | 7 |
| 6 | 3 |
| 10 | 8 |
- 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

