I try to plot a bar graph with a pre-defined number of grid lines like below. However, once I plot it, some yticklabels (A_2,A_3,etc) have not shown (only A_1, A_5, A_9,A_13,A_17 shown). I want to keep all ytick labels, but the gridline should be the same as x axis. Do you have any ideas to fix it?
import matplotlib.pyplot as plt
import numpy as np
mdict={"Column1":["A_" str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
# Create a dataframe
df=pd.DataFrame(mdict)
# Set plot params
fig, ax = plt.subplots(figsize=(12,8))
ax.barh(df.Column1,df.Value, color="darkgray",edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)
# ax.set_yticklabels(list(df_cor.Country.values.tolist()), fontsize=15)
major_ticks_top=np.linspace(0,20,6)
minor_ticks_top=np.linspace(0,20,6)
ax.set_xticks(major_ticks_top)
ax.set_yticks(minor_ticks_top)
ax.grid(alpha=0.2,color="black")
plt.show()
CodePudding user response:
I wouldn't explicitly set the ticks and labels but modify the output matplotlib generates:
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import MultipleLocator
mdict={"Column1":["A_" str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
df=pd.DataFrame(mdict)
fig, ax = plt.subplots(figsize=(12,8))
ax.barh(df.Column1, df.Value, color="darkgray", edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)
#set every fourth tick
n=4
ax.xaxis.set_major_locator(MultipleLocator(n))
ax.grid(alpha=0.2,color="black")
#remove unwanted gridlines on the y-axis
ygrd_lines = ax.get_ygridlines()
[grd_line.set_visible(False) for i, grd_line in enumerate(ygrd_lines) if i%n]
plt.show()
Methods used:
MultipleLocator() setting ticks at defined intervals
.get_ygridlines returning gridlines as a list of Line2D objects for further modification