marxin
marxin

Reputation: 725

Custom background sections for matplotlib figure

I would like to define colors sections (blue: [0-15000], green: [15000-23000], red[23000,]) that should be used for y-values. Is it somehow possible in matplotlib?

Graph

Upvotes: 2

Views: 1784

Answers (1)

ASGM
ASGM

Reputation: 11381

You can color regions on a matplotlib plot using collections.BrokenBarHCollection:

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()

Upvotes: 5

Related Questions