设置 Matplotlib 图表 X 轴的顺序和间距

问题描述 投票:0回答:1

我想创建一个具有特定 x 轴值序列“时间间隔”(0、6、24、114、228)的绘图,同时确保刻度之间的间距相等。

使用“时间”作为 int 变量时,x 轴值按顺序排列,但间隔不等。

x 轴间距不等的绘图: plot with not equally spaced x-axis

当我更改“时间”的数据类型来反对时,绘图很好,但 x 轴值符合我想要的顺序。

顺序错误的绘图: plot with wrong order

# Calculate the sum of weighted_delta_13C at each time point and for each category
sum_df = df.groupby(['time', 'Category'])['weighted_delta_13C'].sum().reset_index()

# Plotting
plt.figure(figsize=(10, 6))

# Iterate over each category to plot its summed values
for category in sum_df['Category'].unique():
    category_data = sum_df[sum_df['Category'] == category]
    plt.plot(category_data['time'], category_data['weighted_delta_13C'], marker='o', linestyle='-', label=f'Category {category}')

plt.title('Sum of weighted_delta_13C at Each Time Point')
plt.xlabel('Time')
plt.ylabel('Sum of weighted_delta_13C')
plt.grid(True)
plt.xticks(sum_df['time'].unique())  # Set the x-ticks to match the time points
plt.legend()
plt.show()

我尝试了这两种解决方案:

1:

n = 12
a = np.arange(n)
x = 2**a
y = np.random.rand(n)

fig = plt.figure(1, figsize=(7,7))
ax1  = fig.add_subplot(211)
ax2  = fig.add_subplot(212)

ax1.plot(x,y)
ax1.xaxis.set_ticks(x)

ax2.plot(a, y) #we plot y as a function of a, which parametrizes x
ax2.xaxis.set_ticks(a) #set the ticks to be a
ax2.xaxis.set_ticklabels(x) # change the ticks' names to x

2:

field = "Day"
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ax = df.set_index(field).loc[day_order].plot(kind="bar", legend=False)
ax.set_ylabel("Value")
python matplotlib plot line
1个回答
0
投票

您应该尝试将唯一的时间值映射到它们的位置以保持相等的间距。你应该有这样的东西:

# Get unique time values and map them to their positions
unique_times = sum_df['time'].unique()
time_mapping = {time: index for index, time in enumerate(unique_times)}

# Map time values to their respective positions
sum_df['time_mapped'] = sum_df['time'].map(time_mapping)

# Plotting
plt.figure(figsize=(10, 6))

# Iterate over each category to plot its summed values
for category in sum_df['Category'].unique():
    category_data = sum_df[sum_df['Category'] == category]
    plt.plot(category_data['time_mapped'], category_data['weighted_delta_13C'], marker='o', linestyle='-', label=f'Category {category}')


plt.xticks(ticks=range(len(unique_times)), labels=unique_times)# Set the x-ticks to match the time points
© www.soinside.com 2019 - 2024. All rights reserved.