Quiero mostrar valores de cadena para pyqtgraph
en el eje x en pyqtgraph
. En este momento no puedo averiguar cómo hacer eso.
Ex:
x = ['a', 'b', 'c', 'd', 'e', 'f'] y = [1, 2, 3, 4, ,5, 6] pg.plot(x, y)
Cuando bash pasar la matriz de cadenas a la variable x
, intenta convertirla en flotante y rompe la GUI con el mensaje de error.
Por lo general, en pyqtgraph cuando se trata de cadenas de ejes personalizadas, la subclase de personas AxisItem y anula las cadenas de verificación con las cadenas que desean que se muestren.
Ver, por ejemplo, pyqtgraph: cómo trazar series de tiempo (fecha y hora en el eje x)?
Pyqtgraphs axisitem también tiene un setTicks incorporado que le permite especificar los ticks que se mostrarán, esto podría hacerse para un problema simple como este en lugar de subclasificar el AxisItem.
El trazado con una cadena personalizada en el eje x podría hacerse así.
xdict = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f'}
o usando
x = ['a', 'b', 'c', 'd', 'e', 'f'] xdict = dict(enumerate(x))
from PyQt4 import QtCore import pyqtgraph as pg x = ['a', 'b', 'c', 'd', 'e', 'f'] y = [1, 2, 3, 4, 5, 6] xdict = dict(enumerate(x)) win = pg.GraphicsWindow() stringaxis = pg.AxisItem(orientation='bottom') stringaxis.setTicks([xdict.items()]) plot = win.addPlot(axisItems={'bottom': stringaxis}) curve = plot.plot(list(xdict.keys()),y) if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_()
Este es un método más genérico que se puede cambiar fácilmente a todo tipo de cosas divertidas, por ejemplo, convertir una marca de tiempo de Unix en una fecha.
from PyQt4 import QtCore import pyqtgraph as pg import numpy as np class MyStringAxis(pg.AxisItem): def __init__(self, xdict, *args, **kwargs): pg.AxisItem.__init__(self, *args, **kwargs) self.x_values = np.asarray(xdict.keys()) self.x_strings = xdict.values() def tickStrings(self, values, scale, spacing): strings = [] for v in values: # vs is the original tick value vs = v * scale # if we have vs in our values, show the string # otherwise show nothing if vs in self.x_values: # Find the string with x_values closest to vs vstr = self.x_strings[np.abs(self.x_values-vs).argmin()] else: vstr = "" strings.append(vstr) return strings x = ['a', 'b', 'c', 'd', 'e', 'f'] y = [1, 2, 3, 4, 5, 6] xdict = dict(enumerate(x)) win = pg.GraphicsWindow() stringaxis = MyStringAxis(xdict, orientation='bottom') plot = win.addPlot(axisItems={'bottom': stringaxis}) curve = plot.plot(list(xdict.keys()),y) if __name__ == '__main__': import sys if sys.flags.interactive != 1 or not hasattr(QtCore, 'PYQT_VERSION'): pg.QtGui.QApplication.exec_()
Captura de pantalla del ejemplo:
Me resulta más fácil preparar una lista de índices y una lista de sus cadenas y luego zip
juntas:
ticks = [list(zip(range(5), ('a', 'b', 'c', 'd', 'e')))]
Puede obtener un AxisItem existente de un PlotWidget así:
pw = pg.PlotWidget() xax = pw.getAxis('bottom')
Y, finalmente, establecer las garrapatas del eje de esta manera:
xax.setTicks(ticks)
Por lo que puedo decir, PlotWidgets incluye automáticamente AxisItems ‘bottom’ y ‘left’, pero puede crear y agregar otros si lo desea.