Dail
Dail

Reputation: 4606

Alternate grid background color in MatplotLib

please take a look at the image below:

MatplotLib

The code to create the chart on the left is:

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.grid(axis='y')
plt.savefig("test_transparent.png", transparent=True)
plt.show()

How can I alternate the grid background color to create a chart like the one on the right?

So basically i have to remove the X axis and set the alternate background color for the horizontal rows.

I would like to create those colored areas without setting the steps of Y axis (0, 0.25, 0.50 and so on..) matplotlib is using. MatplotLib set them automatically, it is ok for me i just need to alternate colors.

Thanks

Upvotes: 1

Views: 2128

Answers (1)

JohanC
JohanC

Reputation: 80329

You could extract a list of yticks and create horizontal spans for them.

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
plt.plot(t, s)
plt.grid(axis='y')
yticks, _ = plt.yticks()
for y0, y1 in zip(yticks[::2], yticks[1::2]):
    plt.axhspan(y0, y1, color='black', alpha=0.1, zorder=0)
plt.yticks(yticks)  # force the same yticks again
plt.show()

example plot

Upvotes: 4

Related Questions