Matteo_Sid
Matteo_Sid

Reputation: 392

How can I customize mplfinance.plot?

I've made a python script to convert a csv file in a candlestick like this using mpl_finance, this is the script:

import matplotlib.pyplot as plt
from mpl_finance import candlestick_ohlc
import pandas as pd
import matplotlib.dates as mpl_dates

plt.style.use('ggplot')

# Extracting Data for plotting
data = pd.read_csv('CSV.csv')
ohlc = data.loc[:, ['Date', 'Open', 'High', 'Low', 'Close']]
ohlc['Date'] = pd.to_datetime(ohlc['Date'])
ohlc['Date'] = ohlc['Date'].apply(mpl_dates.date2num)
ohlc = ohlc.astype(float)

# Creating Subplots
fig, ax = plt.subplots()
plt.axis('off')
fig.patch.set_facecolor('black')

candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.8)

plt.show()

enter image description here

Now I need to do the same thing but using mplfinance instead of mpl_finance and I've tried like this:

import mplfinance as mpf
# Load data file.
df = pd.read_csv('CSV.csv', index_col=0, parse_dates=True)

# Plot candlestick.
# Add volume.
# Add moving averages: 3,6,9.
# Save graph to *.png.
mpf.plot(df, type='candle', style='charles',
        title='',
        ylabel='',
        ylabel_lower='',
        volume=True, 
        mav=(3,6,9), 
        savefig='test-mplfiance.png')

And I have this result: enter image description here
So, now I need to change background color from white to black, remove grid and remove axes but I have no idea how to do it. Thanks to all will spend time for reply me.

[EDIT]: this is an old question I've ade when mpl_finance was at It's first stage, now a lot of things are changed and this question is obsolete.

Upvotes: 21

Views: 52260

Answers (4)

user3786933
user3786933

Reputation: 107

Never to late for a better style, I also don't like any of the default styles so I made this one, I copied the colors from binance dark mode.

binance_dark = {
    "base_mpl_style": "dark_background",
    "marketcolors": {
        "candle": {"up": "#3dc985", "down": "#ef4f60"},  
        "edge": {"up": "#3dc985", "down": "#ef4f60"},  
        "wick": {"up": "#3dc985", "down": "#ef4f60"},  
        "ohlc": {"up": "green", "down": "red"},
        "volume": {"up": "#247252", "down": "#82333f"},  
        "vcedge": {"up": "green", "down": "red"},  
        "vcdopcod": False,
        "alpha": 1,
    },
    "mavcolors": ("#ad7739", "#a63ab2", "#62b8ba"),
    "facecolor": "#1b1f24",
    "gridcolor": "#2c2e31",
    "gridstyle": "--",
    "y_on_right": True,
    "rc": {
        "axes.grid": True,
        "axes.grid.axis": "y",
        "axes.edgecolor": "#474d56",
        "axes.titlecolor": "red",
        "figure.facecolor": "#161a1e",
        "figure.titlesize": "x-large",
        "figure.titleweight": "semibold",
    },
    "base_mpf_style": "binance-dark",
}

can = pd.read_csv("data1.csv", parse_dates=True, index_col=0)
# Plot the candlestick chart
mpf.plot(
    can,
    type="candle",
    style=binance_dark,
    title="BTCUSDT",
    ylabel="Price ($)",
    ylabel_lower="Volume",
    volume=True,
    mav=(2, 4, 6),
    update_width_config=dict(candle_linewidth=0.5, candle_width=0.5),
)

Binance dark theme plot

Upvotes: 3

data2wealth
data2wealth

Reputation: 463

The best way to do this is to define your own style using mpf.make_mpf_style() rather than using the default mpf styles.

If using external axes method in mplfinance, you can plot multiple charts as below:

# add your own style by passing in kwargs    
s = mpf.make_mpf_style(base_mpf_style='charles', rc={'font.size': 6})
fig = mpf.figure(figsize=(10, 7), style=s) # pass in the self defined style to the whole canvas
ax = fig.add_subplot(2,1,1) # main candle stick chart subplot, you can also pass in the self defined style here only for this subplot
av = fig.add_subplot(2,1,2, sharex=ax)  # volume chart subplot
mpf.plot(price_data, type='candle', ax=ax, volume=av)

The default mpf styles are as below. I believe 'mike' and 'nighclouds' have dark background, not 100% sure about others, you can choose to work on top of these two.

In [5]:
mpf.available_styles()
Out[5]:
['binance',
 'blueskies',
 'brasil',
 'charles',
 'checkers',
 'classic',
 'default',
 'mike',
 'nightclouds',
 'sas',
 'starsandstripes',
 'yahoo']

Link to visualize the default mplfinance styles enter image description here

The arguments that can be passed in mpf.make_mpf_style() are as below, you can use base_mpf_style, facecolor, gridcolor, gridstyle, gridaxis, rc to customise your own style, and give it a name by using style_name. You can play around with these arguments to see how they turn out.

def _valid_make_mpf_style_kwargs():
    vkwargs = {
        'base_mpf_style': { 'Default'     : None,
                            'Validator'   : lambda value: value in _styles.keys() },

        'base_mpl_style': { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) }, # and is in plt.style.available

        'marketcolors'  : { 'Default'     : None, # 
                            'Validator'   : lambda value: isinstance(value,dict)  },

        'mavcolors'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,list) },  # TODO: all([mcolors.is_color_like(v) for v in value.values()])

        'facecolor'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'edgecolor'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'figcolor'      : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'gridcolor'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'gridstyle'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'gridaxis'      : { 'Default'     : None,
                            'Validator'   : lambda value: value in [ 'vertical'[0:len(value)], 'horizontal'[0:len(value)], 'both'[0:len(value)] ] },

        'y_on_right'    : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,bool) },

        'rc'            : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,dict) },

        'style_name'    : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

    }
    _validate_vkwargs_dict(vkwargs)
    return vkwargs

Upvotes: 18

Mehrnoush Haghighat
Mehrnoush Haghighat

Reputation: 97

First you should upgrade your package to the latest version, then in your code, you can write: mpf.plot(......, axisoff= True) in my experience sometimes when using "axisoff= True", it is usefull to use figscale to obtain better results.

Upvotes: 2

Moobi Cool
Moobi Cool

Reputation: 41

To hide axes add this:

axisoff=True

Upvotes: 3

Related Questions