matplotlib图的自定义背景部分

时间:2013-04-07 11:31:52

标签: matplotlib

我想定义应该用于y值的颜色部分(蓝色:[0-15000],绿色:[15000-23000],红色[23000,])。在matplotlib中它是否可行?

Graph

1 个答案:

答案 0 :(得分:4)

您可以使用collections.BrokenBarHCollection

为matplotlib图上的区域着色
import matplotlib.pyplot as plt
import matplotlib.collections as collections

fig = plt.figure()
ax = fig.add_subplot(111)

# Plot your own data here
x = range(0, 30000)
y = range(0, 30000)
ax.plot(x, y)

xrange = [(0, 30000)]
yrange1 = (0, 15000)
yrange2 = (15000, 23000)
yrange3 = (23000, 30000)

c1 = collections.BrokenBarHCollection(xrange, yrange1, facecolor='blue', alpha=0.5)
c2 = collections.BrokenBarHCollection(xrange, yrange2, facecolor='green', alpha=0.5)
c3 = collections.BrokenBarHCollection(xrange, yrange3, facecolor='red', alpha=0.5)

ax.add_collection(c1)
ax.add_collection(c2)
ax.add_collection(c3)

plt.show()