简体   繁体   English

在Matplotlib中自定义Y轴比例

[英]Customizing the Y-Axis scale in Matplotlib

I have plotted some horizontal lines on a Candlestick OHLC chart; 我在烛台OHLC图表上绘制了一些水平线; however, my objective is to get the chart to show the value of each of these lines on the Y-Axis. 但是,我的目标是使图表在Y轴上显示每条线的值。 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: 这是我得到的输出:

在此处输入图片说明

Is there a way to show all the prices on the Y-Axis? 有没有办法在Y轴上显示所有价格?

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. 您可以使用Axes类的get_yticks函数获取图表当前刻度位置的列表,追加希望其他刻度出现的位置,然后使用set_yticks函数更新图表。

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): 或者,如果轴开始变得有点杂乱,则可以使用text功能在右端(或适合的任何位置)标记线条:

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. 您可能需要调整x轴的范围以适合标签。

两种技术的输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM