AsTeR
AsTeR

Reputation: 7521

Differentiate style for a grid depending on axis in matplotlib

I am trying to give a different to my grid along the x axis and the y axis.

Though when I call ax.grid it seems to hide the grid instead of configuring it.

import matplotlib.pyplot as plt
import numpy

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
ax.grid(axis='x', linestyle="-", linewidth=1)  # doesn't work
ax.grid(axis='y', linestyle="--", linewidth=1)  # doesn't work
plt.scatter(x, y)
plt.grid()
plt.show()

Current state

Without the ax.grid calls, the grid appears but the style is not what I want.

Without ax.grid calls

Upvotes: 1

Views: 122

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

Just remove plt.grid works for me:

x = np.arange(0, 1, 0.05)
y = np.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(np.arange(0, 1, 0.1))
ax.set_yticks(np.arange(0, 1., 0.1))
ax.grid(axis='x', linestyle="-", linewidth=1)  # doesn't work
ax.grid(axis='y', linestyle="--", linewidth=1)  # doesn't work
ax.scatter(x, y)

# plt.grid()
plt.show()

Output:

enter image description here

Upvotes: 1

Related Questions