如何在matplotlib pyplot中将标签添加到yaxis中的interval group?

2024-04-26 09:42:15 发布

您现在位置:Python中文网/ 问答频道 /正文

参照这个stackoverflow线程Specifying values on x-axis,生成下图。在

enter image description here

我想像这样在上图中添加间隔名。 enter image description here

如何在y轴的每个间隔组中添加这样的间隔组名?在


Tags: 间隔onstackoverflow线程valuesaxisspecifying
1条回答
网友
1楼 · 发布于 2024-04-26 09:42:15

这是一种创建双轴并修改其刻度标签和位置的方法。这里的技巧是在现有的记号之间找到中间位置loc_new,用于放置字符串Interval i。你只需要玩一会儿就能得到你想要的数字。在

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

enter image description here

相关问题 更多 >