3

This is the code I am using to plot stock price charts with mplfinance and I would like the graph to be log scaled. How can I accomplish this?

import mplfinance as mpf

# Data reading and processing steps omitted

mpf.plot(data, type='line')
Daniel Goldfarb
  • 6,937
  • 5
  • 29
  • 61
JakeBoggs
  • 274
  • 4
  • 17
  • what do you get when do `ax = mpf.plot(data, type='line'); print(ax)`? – Quang Hoang Nov 06 '20 at 20:39
  • @QuangHoang `None` – JakeBoggs Nov 06 '20 at 20:41
  • That's pretty bad API, they could have return either the `fig` or `ax` instance they draw on. – Quang Hoang Nov 06 '20 at 20:43
  • After importing `matplotlib.pyplot as plt`, call `ax = plt.gca()`. Now you should be able to set `ax.set_yscale('log')`. Does this work? I cannot check since you did not provide a [MWE](https://stackoverflow.com/help/minimal-reproducible-example) – Timo Nov 06 '20 at 22:56
  • @Timo No, I'm not using matplotlib directly, it's just the library that mplfinance is built with – JakeBoggs Nov 07 '20 at 06:30
  • Have you tried it? Alternatively you have to alter `mpf.plot()` locally such that it returns a `fig` or `ax` instance. – Timo Nov 07 '20 at 09:29
  • @QuangHoang - as you can see from the answer below, the Figure and all Axes objects are returned if you request it. By default, you don't need it for most use-cases. – Daniel Goldfarb Nov 10 '20 at 12:59

2 Answers2

3

Here's the solution I came up with:

import mplfinance as mpf
from matplotlib import pyplot as plt

# Data reading and processing steps omitted

fig, axlist = mpf.plot(data, type='line', returnfig=True)
ax = axlist[0]
ax.set_yscale('log')
plt.show()
JakeBoggs
  • 274
  • 4
  • 17
  • This is the best answer. Anyone who would like to add this code to mplfinance, by creating kwarg `yscale=` for method `mpf.plot()`, please feel free to **fork/clone** [**the repository**](https://github.com/matplotlib/mplfinance) and submit a PR for the change. The code would then become simply: `mpf.plot(data, type='line', yscale='log')` – Daniel Goldfarb Nov 10 '20 at 13:03
2

@JakeBoggs worked, but then the text formatting was scientific notation. For anybody else who is looking into this, I would recommend converting the axis back using a ScalarFormatter

import mplfinance as mpf
from matplotlib import pyplot as plt
from matplotlib.ticker import ScalarFormatter

# Data reading and processing steps omitted

fig, axlist = mpf.plot(data, type='line', returnfig=True)
ax = axlist[0]
ax.set_yscale("log")
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.yaxis.set_minor_formatter(ScalarFormatter())
plt.show()

Kenan
  • 41
  • 1
  • 2