Python:向步骤图添加文本

标签 python matplotlib

假设我正在使用以下代码绘制一个非常基本的步骤图:

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6] 
y = [0.5, 0.22, 0.75, 1, 0.9, 1.2]
text = ['H', 'F', 'E', 'F', 'IT', 'M']
plt.step(x, y,'k-', where='post')
plt.show()

enter image description here

如何在每行或条的顶部显示 text 列表?因此,在栏顶部的 x=1 和 x=2 之间,有 'H',然后在 x=2 和 x=3 之间>,有'F',依此类推...

最佳答案

您可以使用 text() 添加任意文本方法。默认情况下,此方法使用数据坐标,因此您可以使用 y 数据加上偏移量,但您需要截取最后一个值,因为它没有绘制在图表中。按照固定的间隔,您可以使用 numpy.arange() 获取文本的 x 坐标。

import numpy as np
text_x = np.arange(1.5, 5.6)
text_y = [yval+0.06 for yval in y[:-1]]

for t, tx, ty in zip(text[:-1], text_x, text_y):
    plt.text(tx, ty, t)

bar graph with labels results from adding code in my answer to OP's question.

关于Python:向步骤图添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27438631/

相关文章:

python - pandas plot 在 ipython notebook 中不显示为内联

python - 防止 xticks 与 yticks 重叠

python - TypeError: a bytes-like object is required, not 'str' – 在Python中保存JSON数据

python - 动态添加属性到 Django 模型

python - Django、Python继承: Exclude some fields from superclass

python - 添加 UTC 时间轴以以时间格式绘制本地时间

python - 如何将图像文件从 S3 存储桶直接读入内存?

python - 为什么连接总是被拒绝?

python - 在 Django 中通过 self.request.user 过滤对象列表

python - text.usetex : True in matplotlib 有什么好处