在 Matplotlib 中自定义 Y 轴刻度

Customizing the Y-Axis scale in Matplotlib

我在烛台 OHLC 图表上绘制了一些水平线;然而,我的 objective 是让图表显示 Y 轴上每条线的值。 这是我的代码:

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()

这是我得到的输出:

有没有办法在 Y 轴上显示所有价格?

您可以使用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函数来更新图表。

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

要更改刻度标签的颜色以匹配线条:

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

或者,如果轴开始变得有点混乱,您可以使用 text function 标记右手端(或任何适合的地方)的线:

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

您可能需要调整 x 轴的范围以适应标签。