[英]Python: Add text to step plot
Say that I am plotting a very basic step plot with this code: 假设我正在用这段代码绘制一个非常基本的步骤图:
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()
How can I display on the top of each lines or bar, the text
list? 如何在每行或条的顶部显示
text
列表? So between x=1 and x=2
on the top of the bar, have 'H'
, then between x=2 and x=3
, have 'F'
, and so on... 因此,在条形图顶部的
x=1 and x=2
之间,有'H'
,然后在x=2 and x=3
,有'F'
,依此类推......
You can add arbitrary text using the text()
method. 您可以使用
text()
方法添加任意文本。 By default, this method uses data coordinates, so you can use your y data plus an offset, but you'll need to slice off the last value since it's not plotted in your graph. 默认情况下,此方法使用数据坐标,因此您可以使用y数据加上偏移量,但是您需要切掉最后一个值,因为它没有在图表中绘制。 With your regular intervals, you can get the x coordinates for the text with
numpy.arange()
. 使用常规间隔,您可以使用
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.