Stücke
Stücke

Reputation: 993

Move grid inbetween bars

Is there a way to move the horizontal grid lines in the left plot in-between the bars whilst keeping the y labels at the same position?

enter image description here

import matplotlib.pyplot as plt

y_positions = list(range(20))
x1 = list(range(20))
x2 = list(range(0, 200, 10))

fig, axes = plt.subplots(ncols=2, sharey=True,)

axes[0].barh(y_positions, x1, align='center')
axes[0].set_yticks(list(range(20)))
axes[0].set_yticklabels([str(x)+"foo" for x in range(20)])
axes[0].grid(axis='x')
axes[0].grid(axis='y')

axes[1].hlines(y_positions, xmin=0, xmax=x1)
axes[1].plot(y_positions, x1, "*")

plt.show()

Upvotes: 0

Views: 143

Answers (1)

JohanC
JohanC

Reputation: 80409

You can use the minor ticks for the grid. Here is an example:

import matplotlib.pyplot as plt

y_positions = list(range(20))
x1 = list(range(20))
x2 = list(range(0, 200, 10))

fig, axes = plt.subplots(ncols=2, sharey=True, )

axes[0].barh(y_positions, x1, align='center', height=0.6)
axes[0].set_yticks(x1)
axes[0].set_yticks([x + 0.5 for x in x1[:-1]], minor=True)  # set minor ticks at the halves
axes[0].set_yticklabels([str(x) + "foo" for x in range(20)])
axes[0].grid(axis='x')
axes[0].grid(axis='y', which='minor')  # set the grid on the minor ticks
axes[0].tick_params(axis='y', which='minor', length=0)  # hide minor tick marks
axes[0].margins(y=0.02)  # less whitespace (padding) at top and bottom

axes[1].hlines(y_positions, xmin=0, xmax=x1)
axes[1].plot(y_positions, x1, "*")
axes[1].tick_params(axis='y', which='minor', length=0)

plt.show()

grid lines in between the bars

Upvotes: 1

Related Questions