简体   繁体   English

如何在matplotlib pyplot中的y轴上向间隔组添加标签?

[英]How to add label to interval group in y-axis in matplotlib pyplot?

With reference to this stackoverflow thread Specifying values on x-axis , following figure is generated . 参照该stackoverflow线程, 在x轴上指定值 ,将生成下图。

在此处输入图片说明

I want to add interval name in the above figure like this way. 我想以这种方式在上图中添加间隔名称。 在此处输入图片说明

How to add such interval group name in every interval group in y-axis? 如何在y轴的每个间隔组中添加这样的间隔组名称?

This is one way of doing it by creating a twin axis and modifying its tick labels and positions. 这是通过创建双轴并修改其刻度标签和位置来实现的。 Trick here is to find the middle positions loc_new between the existing ticks for placing your strings Interval i . 这里的技巧是在现有的刻度之间找到loc_new的中间位置,以放置字符串Interval i You just need to play around a bit to get exactly the figure you want. 你只需要张望了一下发挥, 达到您想要的数字。

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()

x = np.array([0,1,2,3])
y = np.array([0.650, 0.660, 0.675, 0.685])
my_xticks = ['a', 'b', 'c', 'd']
plt.xticks(x, my_xticks)
plt.yticks(np.arange(y.min(), y.max(), 0.005))
plt.plot(x, y)
plt.grid(axis='y', linestyle='-')

ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())

loc = ax2.get_yticks()
loc_new = ((loc[1:]+loc[:-1])/2)[1:-1]
ax2.set_yticks(loc_new)

labels = ['Interval %s' %(i+1) for i in range(len(loc_new))]
ax2.set_yticklabels(labels)
ax2.tick_params(right=False) # This hides the ticks on the right hand y-axis
plt.show()

在此处输入图片说明

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

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