python - 如何在 matplotlib pyplot 中将标签添加到 y 轴的区间组?

标签 python matplotlib

引用这个stackoverflow线程Specifying values on x-axis ,生成如下图。

enter image description here

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

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

最佳答案

这是通过创建双轴并修改其刻度标签和位置来实现的一种方法。这里的技巧是找到现有刻度之间的中间位置 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

关于python - 如何在 matplotlib pyplot 中将标签添加到 y 轴的区间组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55937501/

相关文章:

matplotlib - matplotlib 的 axvline 中的错误?

python - Django 表单的赞成票和反对票按钮

python - 在 heroku 上部署时运行一次 python 脚本

python - 坐标图的刻度轴刻度标签

python - Pyplot 交互式缩放

python - 在 Python 中建立无向图模型

python - 为什么 'module' 对象在 python opencv 中不可调用?

python - 属性错误: module 'discord' has no attribute 'ui' when trying to create button in discord. py

python - 在 python 中演奏和弦

python - 我们如何从 matplotlib 导航工具添加希腊符号作为轴标签?