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

如何为Python gnuplotlib绘图添加自定义X轴刻度?

解决gnuplotlib自定义X轴刻度标签无效的问题

问题出在你传递给xtics参数的格式上,gnuplotlib要求自定义刻度的元组顺序是**(位置, 标签)**,而非你写的(标签, 位置)。另外也可以直接传入符合gnuplot语法的字符串来定义刻度。

修复方案1:调整元组顺序

import numpy as np
import gnuplotlib as gp

xtics_positions = [0, 2, 4, 6, 8]
xtics_labels = ["zero", "two", "four", "six", "eight"]
# 修正顺序:(位置, 标签)
xtics = [(pos, label) for pos, label in zip(xtics_positions, xtics_labels)]

datapoints = np.array([ 0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0, 11,  5,  5,  2, 21,  1, 21,  0,  8, 62, 56,  0,  0,  0,  6,  3, 32,  7, 17,  1,  6, 10, 12,  0, 21, 11,  6, 14,  1, 15, 25, 30, 17, 11,  6,  4,  0])
gp.plot(datapoints, xtics=xtics)

修复方案2:使用gnuplot原生语法字符串

如果你更习惯gnuplot的原生写法,可直接构造字符串传入:

import numpy as np
import gnuplotlib as gp

xtics_str = "0 'zero', 2 'two', 4 'four', 6 'six', 8 'eight'"

datapoints = np.array([ 0,  1,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0, 11,  5,  5,  2, 21,  1, 21,  0,  8, 62, 56,  0,  0,  0,  6,  3, 32,  7, 17,  1,  6, 10, 12,  0, 21, 11,  6, 14,  1, 15, 25, 30, 17, 11,  6,  4,  0])
gp.plot(datapoints, xtics=xtics_str)

两种方式都能正确渲染自定义的X轴刻度标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:20:03