我想给pyplot背景上色

时间:2019-12-07 13:26:26

标签: python matplotlib colors

我想用与所附图像相似的方式对pyplot的背景进行色带设置。我对绘制随机线没有问题,我只希望它覆盖在某些波段上,以便从视觉上确定事物发生变化的点。波段必须在x轴上具有固定宽度(0-3、3-7、7- ..等)。y值在图与图之间不是恒定的,因此,波段需要达到0-yMin (我正在处理深度)每个情节。 我已经尝试过尝试数组/条形图以及导入和拉伸图像,但是似乎都没有用。 What I want

1 个答案:

答案 0 :(得分:1)

您可以使用ymin方法(see reference)来设置图形背景的不同颜色。

请注意,ymaxxmin参数是指图形上的实际y值,而xmaximport matplotlib.pyplot as plt import random # generate random data elevation = [random.randrange(-y -1, 0) for y in range(10)] distance = range(10) # get reference to axes fig, ax = plt.subplots() # plot data with a yellow line ax.plot(distance, elevation, 'y', linewidth=3) # format axes ax.grid() ax.margins(0) ax.set_ylabel('elevation (m)') ax.set_xlabel('position') ax.set_ylim([min(elevation) - 1, max(elevation) + 1]) # get range of axes ymin, ymax = ax.get_ylim() xmax = max(distance) # set background colours ax.axhspan(ymin, ymax, 0 / xmax, 3 / xmax, facecolor='green') ax.axhspan(ymin, ymax, 3 / xmax, 8 / xmax, facecolor='brown') ax.axhspan(ymin, ymax, 8 / xmax, 9 / xmax, facecolor='blue') # display graph plt.show() 参数应缩放为0到1之间的值(0表示x轴的起点,1表示x轴的终点)。

{{1}}

graph with background color