PyQtGraph - 如何设置轴的间隔

时间:2016-12-10 18:27:28

标签: python pyqt5 pyqtgraph

以下是我编写的一个函数,它基于分数元组列表(分数及其频率)创建图表

def initialise_chart(self, scores):

    pg.setConfigOption("background", "w")
    pg.setConfigOption("foreground", "k")

    results_graph = pg.PlotWidget()
    self.chart_results.addWidget(results_graph)
    results_graph.plot([i[0] for i in scores], [i[1] for i in scores], pen={'color': "#006eb4"})
    results_graph.setLabels(left="Frequency", bottom="Scores")
    results_graph.setXRange(0, self.max_mark, padding=0)

这会生成以下图表: enter image description here

有没有办法设置y轴的间隔,以便数字以1为单位上升,但范围仍然是自动调整的?例如。示例图表的y轴上显示的唯一数字是0,1,2

1 个答案:

答案 0 :(得分:1)

您必须更改AxisItem上的刻度,例如:

import pyqtgraph as pg
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui

app = pg.mkQApp()

pw = pg.PlotWidget(title="Example")
x = np.arange(20)
y = x**2/150
pw.plot(x=x, y=y, symbol='o')
pw.show()
pw.setWindowTitle('Example')

ax = pw.getAxis('bottom')  # This is the trick
dx = [(value, str(value)) for value in list((range(int(min(x.tolist())), int(max(x.tolist())+1))))]
ax.setTicks([dx, []])

ay = pw.getAxis('left')  # This is the trick
dy = [(value, str(value)) for value in list((range(int(min(y.tolist())), int(max(y.tolist())+1))))]
ay.setTicks([dy, []])

if __name__ == '__main__':
    import sys

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

在:

enter image description here

后:

enter image description here