Search code examples
pythonpython-3.xpyqt6pyqtchart

How can I add zero value axis in pyqt charts?


I'm trying add zero value axis in chart by using pyqt.

This picture shows graph plotted by pyqt6 charts:

This picture shows graph plotted by pyqt6 charts

In the above graph, there is no zero value in axis-y. How can I show zero value?

This is my code for axis-y.

self.ob_Chart_Viewer.axis_y.setRange(Config.f_Min, Config.f_Max)
if self.ob_User_Inputs.cb_Axis_Y_Value_Type.currentIndex() + 1 == Config.AxisYValueType.AbsoluteInPercent.value:
        self.ob_Chart_Viewer.axis_y.setTickInterval((Config.f_Max - Config.f_Min) / 10)
        self.ob_Chart_Viewer.axis_y.setTickCount(10)

Solution

  • I provided a solution using matplotlib NOT pyqt charts; I'll leave my answer in case it provides any helpful information given that after I tried using the pyqtcharts, PyQt5, etc. libraries without any luck even importing them, my alternate solution provides an excellent avenue through which to avoid using deprecated libraries that, for me, immediately crashed my sessions.

    You didn't provide any code so I'll give an example solution:

    import numpy as np
    import pandas as pd
    import matplotlib
    import matplotlib.pyplot as plt
    import matplotlib.transforms as transforms
    y = np.linspace(-10, 10, num = 100)
    fig = plt.figure(figsize = (15, 10), num = 1, clear = True)
    ax = plt.subplot(1, 1, 1)
    ax.plot(np.arange(0, len(y), 1), y, color = [0, 0.5, 1], lw = 1.5)
    trans = transforms.blended_transform_factory(ax.get_yticklabels()[0].get_transform(), ax.transData)
    ax.text(0, 0, "{:.2f}".format(0), fontsize = 10, color = [1, 0, 0], transform = trans, ha = 'right', va = 'center')
    emptyVectorForZeroLine = np.zeros([len(y), 1], dtype = float)
    ax.plot(np.arange(0, len(y), 1), emptyVectorForZeroLine, color = [0, 0, 0], lw = 1)
    ax.set_yticks(np.linspace(-9, 9, 10))
    plt.show()
    

    To add a zero tick label on the y-axis:

    trans = transforms.blended_transform_factory(ax.get_yticklabels()[0].get_transform(), ax.transData)
    ax.text(0, 0, "{:.2f}".format(0), fontsize = 10, color = [1, 0, 0], transform = trans, ha = 'right', va = 'center')
    

    To add a horizontal plot line at the value of zero on the y-axis:

    emptyVectorForZeroLine = np.zeros([len(y), 1], dtype = float)
    ax.plot(np.arange(0, len(y), 1), emptyVectorForZeroLine, color = [0, 0, 0], lw = 1)