Skip to main content
 首页 » 编程设计

python之在 matplotlib 图中自定义 xticks

2025年05月04日23findumars

我想绘制一个具有 xticks 的图形,例如从 50 到 100。

到目前为止我尝试了什么:

data_to_plot = data[-90:]  # 90 datapoints 
 
# Create figure 
fig = plt.figure() 
ax = fig.add_subplot(111) 
 
# Plot the value 
ax.plot(data_to_plot/S) 
 
# Set the ticks 
x_ticks = np.arange(50, 140) 
ax.set_xticks(x_ticks) 
 
# Limits 
plt.ylim(0, 1) 
 
# Naming 
plt.title("Cooperation") 
plt.xlabel("Round") 
plt.ylabel("Value") 
plt.show() 

我得到的是这个数字:

而不是 xticks 从 50 到 140 的图形,即列表 [50, 60, 70, . .., 130, 140] 用于 xtick 中的标签。

使用: Python 3、Matplotlib 3.0.2、MacOS 10.13。

请您参考如下方法:

绘制图形时,您还必须指定 x 值。 然后,根据您需要的详细程度,设置 x_ticks。

# Plot the value 
x_ticks = np.arange(50, 140) 
ax.plot(x_ticks,data_to_plot) 
 
# Set the ticks 
ax.set_xticks(np.arange(50, 140,10))