3

Using Mplfinance. I am hoping someone can clarify the correct usage of the 'y_on_right' parameter. I believe I am using mpf.make_addplot() correctly but it will not move the y axis to the other side of the chart. Using the docs provided. TIA.

        mpf.make_addplot(
        df['sentiment'], 
        type='line',
        ax=ax3,
        y_on_right=True,         
        ylabel='Sentiment',
        color='#6f2d84'
        )]

Edit: Add working example of code.

def makeCharts_CountsOHLC(self, props):

fig = props['fig']
df = props['df']
symbol = props['symbol']
start = props['min_date']
end = props['max_date']

# Configure the axes
ax1 = fig.add_subplot(5,1,(1,2))
ax2 = fig.add_subplot(5,1,3, sharex=ax1)
ax3 = fig.add_subplot(5,1,4, sharex=ax1)
ax4 = fig.add_subplot(5,1,5, sharex=ax1)

# Create add plots
aps = [
    mpf.make_addplot(
    df['count_s'], 
    ax=ax2, 
    ylabel='Tweets',
    ),
    
    mpf.make_addplot(
    df['sentiment'], 
    type='bar',
    ax=ax3,
    ylabel='Sentiment',            
    )]

ax1.tick_params(labelbottom=False)
ax2.tick_params(labelbottom=False)
ax3.tick_params(labelbottom=False)

# Functions to add a day to date and format dates 
date_p1 = lambda x: dt.strftime(pd.to_datetime(x) + td(days=1), '%d %b %y')
fmt_date = lambda x: dt.strftime(pd.to_datetime(x), '%d %b %y')

title = f'{symbol} Price and Volume Traded from {fmt_date(start)} until {date_p1(end)}'

# Plot the chart
mpf.plot(
    df,
    type='candle',
    ax = ax1,
    volume = ax4,
    addplot = aps,
    xrotation = 0,
    datetime_format = '%b %d',
    axtitle = title,
    ylabel = 'Price ($USD)',
    tight_layout = True
    )

# Format the prive of the y axis 
mkfunc = lambda x, pos: '%1.1fM' % (x * 1e-6) if x >= 1e6 else '%1.1fK' % (x * 1e-3) if x >= 1e3 else '%1.1f' % x
mkformatter = matplotlib.ticker.FuncFormatter(mkfunc)
ax1.yaxis.set_major_formatter(mkformatter)

# Adjustments to plot and save
plt.subplots_adjust(hspace=0)
plt.savefig(fname=props['save_path'], dpi=self.cconf.get('RESOLUTION'))
plt.close('all')
fig.clear()

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
cwfmoore
  • 225
  • 3
  • 11
  • Do you have the a minimal working example with the plot function? you are using the keyword correctly but you have to add it to an existing plot that has a left y axis – Mohammad Aug 14 '21 at 10:01
  • Added a working example of code. – cwfmoore Aug 14 '21 at 10:07

3 Answers3

2

The y_on_right is not supported in External Axes Mode.

If you would like to change the direction of a specific axis, you can do it directly:

ax3.yaxis.set_label_position("right")
ax3.yaxis.tick_right() 
Daniel Goldfarb
  • 6,937
  • 5
  • 29
  • 61
Mohammad
  • 3,276
  • 2
  • 19
  • 35
2

As for y_on_right in mplfinance, it is false by default and is always displayed on the right side. This is to make the main axis to the left when a moving average is added to a candlestick, for example, when there are two axes. I have drawn an additional plot that is similar to your output for one stock as an example. The number of tweets is unknown, so I substituted volume. To save the graph, create the save information and include it in the main graphing code.

import mplfinance as mpf
import matplotlib.pyplot as plt
import yfinance as yf

symbol = "AAPL"
start, end = "2021-01-01", "2021-07-01"
data = yf.download("AAPL", start=start, end=end)

title = f'\n{symbol} Price and Volume Traded \nfrom {start} until {end}'

apds = [mpf.make_addplot(data.Volume, type='bar', panel=1, ylabel='Tweet', y_on_right=False),
        mpf.make_addplot(data.Close, type='line', mav=(20,50), panel=2, ylabel='EMA', y_on_right=True),
        mpf.make_addplot(data.Volume, type='bar', panel=3, ylabel='Volume', y_on_right=False)
       ]

save = dict(fname='test_mpl_save.jpg',dpi=150, pad_inches=0.25)
mpf.plot(data, 
         type='candle', 
         addplot=apds, 
         volume=False,
         ylabel='Price ($USD)',
         style='starsandstripes',
         title=title, datetime_format=' %a %d',
         #savefig=save
        ) 

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • 1
    kwarg `y_on_right` is actually `None` [by default](https://github.com/matplotlib/mplfinance/blob/master/src/mplfinance/plotting.py#L1069-L1072) because it also depends on the **`style`** used (some styles are `y_on_right=True`, some are `y_on_right=False`). – Daniel Goldfarb Aug 15 '21 at 03:22
  • I learned another thing from your advice. Thank you. – r-beginners Aug 15 '21 at 04:33
2

y_on_right is one of several mplfinance features that is not available in External Axes Mode.

You can see the code here. Some features are necessarily unavailable when in External Axes Mode, for various reasons, but mainly all of them somehow connected to the fact that mplfinance does not have full control over the axes when in External Axes Mode.

While mplfinance does give warnings for some of the features if you try to use them in External Axes Mode, it has been tedious and difficult to ensure that the code contains warnings for all such features that cannot be supported in External Axes Mode. Hopefully in the future all such features will contain warnings if you try to use them in External Axes Mode.

Meanwhile, please be aware that mplfinance documentation strongly discourages the use of External Axes Mode except when you are trying to accomplish something that cannot be accomplished in any other way.

For the record, as of this writting, all of the plot images posted on the page here are of the type that mplfinance can do without the need to resort to External Axes Mode.

Full disclosure: I am the maintainer of the mplfinance package.

P.S. If you do choose to use External Axes Mode, then @Mohammad 's answer is the correct way to do it.

P.P.S. I have started documenting a list of features not supported in External Axes Mode.

Daniel Goldfarb
  • 6,937
  • 5
  • 29
  • 61