简体   繁体   中英

How do you add padding between the x-axis tick marks (not tick labels) and the x-axis in Matplotlib and Seaborn

I have created a heatmap using Seaborn and Matplotlib. I want to figure out how to add padding between the x-axis and the xtickmarks.

I have searched online and found ways to add spacing between the tick labels and the tick marks using axs.tick_params(axis='x', pad=100) and filling in the desired padding value. This is not what I want to figure out.

I have also found ways to add spacing between the x-axis label and the x-axis using axs.set_xlabel("x axis label", fontsize=24, labelpad=100) , this is also not what I am looking for.

Here is my code and current output, with a sketch of the change I am trying to make (move the tick marks away from the axis).

fig, axs = plt.subplots(figsize=(12,12)) 

sns.heatmap(data=heat_df, cmap="Blues", annot=True, annot_kws={'fontsize' : 20 }, xticklabels=[0,1], 
yticklabels=[0,1], square=True, ax=axs)
axs.set_title("Accuracy Score: " + str(accuracy), fontsize=24, pad=100)
axs.set_xlabel("Predicted label", fontsize=24)
axs.set_ylabel("Actual label", fontsize=24)
axs.tick_params(axis='y', labelsize=20)
axs.tick_params(axis='x', labelsize=20, pad=100)

plt.show()

Heatmap with red markings showing desire to move tick marks out away from the axis:

具有所需更改的热图

You can do it by getting a list of the xtick Line2D objects and then manually setting their position. It's not an automatic solution as you may need to tweak the numbers to get the ticks where you want them:

fig, axs = plt.subplots(figsize=(12,12))

heat_df = np.random.randint(0, 10, (2,2))
sns.heatmap(data=heat_df, cmap="Blues", annot=True, annot_kws={'fontsize' : 20 },
            xticklabels=[0,1], yticklabels=[0,1], square=True, ax=axs)
axs.set_xlabel("Predicted label", fontsize=24)
axs.set_ylabel("Actual label", fontsize=24)
axs.tick_params(axis='y', labelsize=20)
axs.tick_params(axis='x', labelsize=20, pad=30)

for line in axs.get_xticklines():
    line.set_data([0, -0.06])

plt.show()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM