给定一组 n 个“坐标”,例如 x=[0, 1, 2, 3, 4]
和 n-1 个“值”y = [10, 20, 30, 40]
我想绘制一个分段常数函数,对于 0 < x <1,它等于 10;对于 1 < x < 2,它等于 20。
换句话说,x 列表包含单元格边界的坐标,而 y 列表表示单元格内该函数的值。绘制此类数据的标准方法是什么?
我也对不规则网格和二维图感兴趣。
最佳答案
对于一维数据,您可以使用条形图。第一个参数是条形的中心,第二个参数是条形的高度。
x=np.asarray([0, 1, 2, 3, 4])
centers=(x[1:]+x[:-1])/2.0
plt.bar(centers,[10, 20, 30, 40],width=1)
对于二维数据,您可以使用 pcolor
和颜色条
# x coordinates of the cells
x=np.asarray([0, 1, 2, 3, 4])
# y coordinates of the cells
y=np.asarray([0,1,2])
# values inside the cells
c = np.asarray([[10, 20, 30, 40], [50,60,70,80]])
# plot the cells
plt.pcolor(x,y,c)
# plot a bar to match colors with values
plt.colorbar()
要绘制非常规网格,pcolor
可以将 x 和 y 的二维数组作为参数:您可以指定每个单元格的 x 和 y 坐标。
请注意,pcolormesh
绘制的内容与 pcolor
相同,但速度更快,这很有用。
关于python - 在 matplotlib 中绘制单元格平均值而不是线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35035615/