Search code examples
python-3.xmatplotlibplotlycandlestick-chart

How to color a candles of candlestick plot with a customized color as shown in the image & reproducible data frame stated below


    import pandas as pd

#create DataFrame
df = pd.DataFrame({'open': [25, 22, 21, 19, 23, 21, 25, 29],
                       'close': [24, 20, 17, 23, 22, 25, 29, 31],
                       'high': [28, 27, 29, 25, 24, 26, 31, 37],
                       'low': [22, 16, 14, 17, 19, 18, 22, 26],
                      'cndle_class':['1', '2D', '3D', '1', '1', '3U', '2U', '2U'],
                  'cndl_bodycolor':['yellow','red','pink','yellow','yellow','pink','green','green'],
                  'cndl_llinecolor':['white','red','red','white','white','green','green','green']},
                       index=pd.date_range("2021-01-01", periods=8, freq="d"))

enter image description here

The plot should look like as shown in above image . Only color is required not the label.


Solution

  • You could define your own candle plot function:

    def plot_candle(df):
        fig, ax = plt.subplots(1, 1, facecolor='black')
        ax.set_facecolor('black')
        
        #define width of candlestick elements
        width = .5
        width2 = .01
    
        #define up and down prices
        up = df[df.close>=df.open]
        down = df[df.close<df.open]
    
        #plot up prices
        plt.bar(up.index, up.close - up.open, width, bottom=up.open, color=up.cndl_bodycolor, edgecolor=up.cndl_llinecolor, zorder=3)
        plt.bar(up.index, up.high - up.close, width2, bottom=up.close, color=up.cndl_llinecolor, zorder=3)
        plt.bar(up.index, up.low - up.open, width2, bottom=up.open, color=up.cndl_llinecolor, zorder=3)
    
        #plot down prices
        plt.bar(down.index, down.close - down.open, width, bottom=down.open, color=down.cndl_bodycolor, edgecolor=up.cndl_llinecolor, zorder=3)
        plt.bar(down.index, down.high - down.open, width2, bottom=down.open, color=down.cndl_llinecolor, zorder=3)
        plt.bar(down.index, down.low - down.close, width2, bottom=down.close, color=down.cndl_llinecolor, zorder=3)
    
    plot_candle(df)
    plt.show()
    

    enter image description here