Home > Software design >  How to set x and y axis columns in python subplot matplotlib
How to set x and y axis columns in python subplot matplotlib

Time:11-24

def plot(self):
    plt.figure(figsize=(20, 5))

    ax1 = plt.subplot(211)
    ax1.plot(self.signals['CLOSE'])
    ax1.set_title('Price')

    ax2 = plt.subplot(212, sharex=ax1)
    ax2.set_title('RSI')
    ax2.plot(self.signals[['RSI']])
    ax2.axhline(30, linestyle='--', alpha=0.5, color='#ff0000')
    ax2.axhline(70, linestyle='--', alpha=0.5, color='#ff0000')
    
    plt.show()

I am plotting two charts in python application. But the x axis values are indexes like 1,2,3,....

But my dataframe has a column self.signals['DATA'] so how can I use it as x axis values?

CodePudding user response:

With set_xticks you set, where the positions are, for example:

ax1.set_xticks([1, 2, 3])

and with set_xticklabels you can define what it says there:

ax1.set_xticklabels(['one', 'two', 'three'])

see https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xticklabels.html for more options.

CodePudding user response:

But the x axis values are indexes like 1,2,3,...

But my dataframe has a column self.signals['DATA'] so how can I use it as x axis values?

I assume you are using pandas and matplotlib.

According to matplotlib documentation, you can simply pass the X and Y values to the plot function.

So instead of calling

ax1.plot(self.signals['CLOSE'])

you can for instance do:

ax1.plot(self.signals['DATA'], self.signals['CLOSE'])

Depending on other arguments, this will do a scatter plot or a line plot. see matplotlib documentation for more fine tuning of your charts.

or you could even try:

plot('DATA', 'CLOSE', data=self.signals)

Quoting documentation:

Call signatures:

plot([x], y, [fmt], *, data=None, **kwargs)

plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

  • Related