BhishanPoudel
BhishanPoudel

Reputation: 17154

Matplotlib: How to make alternative vertical lines of grid dashed?

If I had simple integer x-axis, I could use plt.axvline(value) to get vertical lines, but I am wondering how to get vertical dashed lines when we have string x-axis labels.

setup

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline


np.random.seed(123)

x = np.random.normal(0,1,100)
xx = pd.cut(x,20).to_numpy().astype(str)

yy = np.random.normal(0,1,100)

plt.plot(xx,yy,'o')
plt.xticks(rotation=90)
plt.grid(True)

plt.show()

Required

current output

enter image description here

Upvotes: 2

Views: 1588

Answers (2)

Arne
Arne

Reputation: 10545

plt.xticks() returns the x tick locations and labels, so we can access the locations by indexing with [0]. It turns out this is just a list of consecutive integer values, so we can loop through them and draw the grid lines manually, with a different style for every other one. With plt.grid(True, axis='y') we make sure the automatic grid is drawn only for the y axis, so that this does not interfere with our custom vertical lines.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline


np.random.seed(123)

x = np.random.normal(0,1,100)
xx = pd.cut(x,20).to_numpy().astype(str)

yy = np.random.normal(0,1,100)

plt.plot(xx,yy,'o')
plt.xticks(rotation=90)

############################
# new code below           #
############################

plt.grid(True, axis='y')

for tick in plt.xticks()[0]:
    if tick % 2 == 0:
        plt.axvline(tick, color='gray', linestyle='-', linewidth=1, alpha=.5)
    else:
        plt.axvline(tick, color='red', linestyle='--', linewidth=1, alpha=1)

Custom Grid

Upvotes: 1

Derek O
Derek O

Reputation: 19565

Draw the gridlines yourself, changing the style how you want for every other vertical line.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

np.random.seed(123)

x = np.random.normal(0,1,100)
xx = pd.cut(x,20).astype(str)
yy = np.random.normal(0,1,100)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(xx, yy,'o')
plt.xticks(rotation=90)

for index, xmaj in enumerate(ax.xaxis.get_majorticklocs()):
    if index % 2 == 0:
        ax.axvline(x=xmaj, ls='-', linewidth = 1.0, color = 'grey')
    else:
        ## add line change style/color here
        ax.axvline(x=xmaj, ls='--', linewidth = 1.0, color = 'blue')
for ymaj in ax.yaxis.get_majorticklocs():
    ax.axhline(y=ymaj, ls='-', linewidth = 1.0, color = 'grey')

plt.show()

alternating gridlines image

Upvotes: 1

Related Questions