Search code examples
pythonmatplotlibaxis-labelsquantitative-financecandlestick-chart

Customizing the Y-Axis scale in Matplotlib


I have plotted some horizontal lines on a Candlestick OHLC chart; however, my objective is to get the chart to show the value of each of these lines on the Y-Axis. This is my code:

plt.figure( 1 )
plt.title( 'Weekly charts' )
ax = plt.gca()

minor_locator_w = allweeks
major_formatter_w = yearFormatter

ax.xaxis.set_minor_locator( minor_locator_w )
ax.xaxis.set_major_formatter( major_formatter_w )

candlestick_ohlc(ax, zip(df_ohlc_w[ 'Date2' ].map( mdates.datestr2num ),
                 df_ohlc_w['Open'], df_ohlc_w['High' ],
                 df_ohlc_w['Low'], df_ohlc_w['Close']), width=0.6, colorup= 'g' )

ax.xaxis_date()

ax.autoscale_view()

plt.setp(ax.get_xticklabels(), horizontalalignment='right')

historical_prices_200 = [ 21.53, 22.09, 22.31, 22.67 ]

horizontal_lines = historical_prices_200

x1 = Date2[ 0 ]
x2 = Date2[ len( Date2 ) - 1 ]

plt.hlines(horizontal_lines, x1, x2, color='r', linestyle='-')

plt.show()

This is the output that I am getting:

enter image description here

Is there a way to show all the prices on the Y-Axis?


Solution

  • You can use the get_yticks function of the Axes class to get a list of the chart's current tick locations, append the locations you want additional ticks to appear, then use the set_yticks function to update the chart.

    ax.hlines(horizontal_lines, x1, x2, color="r")
    ax.set_yticks(np.append(ax.get_yticks(), horizontal_lines))
    

    To change the colour of the tick labels to match the lines:

    plt.setp(ax.get_yticklabels()[-len(horizontal_lines):], color="r")
    

    Alternatively, if the axis starts to become a little cluttered, you can use the text function to label the lines at the right-hand end (or anywhere that suits):

    ax.hlines(horizontal_lines, x1, x2, color="r")
    for v in horizontal_lines:
        ax.text(x2, v, v, ha="left", va="center", color="r")
    

    You might need to adjust the limits of the x axis to fit the labels in.

    Output of both techniques