如何在 Matplotlib 和 Seaborn 中的 x 轴刻度线(不是刻度标签)和 x 轴之间添加填充

时间:2021-02-16 14:30:27

标签: python matplotlib seaborn

我使用 Seaborn 和 Matplotlib 创建了一个热图。我想弄清楚如何在 x 轴和 xtickmarks 之间添加填充。

我在网上搜索并找到了使用 Option Explicit Public Sub call_stacko_function() Dim r As Range Set r = ColorCountCustomDates(Range("4:4"), Range("a1").Value, Range("a2").Value, Range("7:7"), RGB(127, 0, 127)) Debug.Print r.Address End Sub Function ColorCountCustomDates(DateRaw As Range, StartDate As Long, EndDate As Long, LineWhereToApplyFunc As Range, CellColor As Long) As Range Dim Rng As Range Dim start_col As Variant Dim end_col As Variant start_col = Application.WorksheetFunction.Match(StartDate, DateRaw, 1) If IsError(start_col) Then start_col = 1 If DateRaw.Cells(1, 1).Offset(0, start_col - 1).Value < StartDate Then start_col = start_col + 1 end_col = Application.WorksheetFunction.Match(EndDate, DateRaw, 1) If IsError(end_col) Then end_col = DateRaw.Parent.Cells(DateRaw.Row, 1).End(xlToRight) 'With LineWhereToApplyFunc.Interior ' .Color = xlNone 'End With Set Rng = Range(LineWhereToApplyFunc.Cells(1, start_col), LineWhereToApplyFunc.Cells(1, end_col)) 'With Rng.Interior ' .Color = CellColor 'End With ' Add OP function call ColorCount Rng Set ColorCountCustomDates = Rng End Function 在刻度标签和刻度线之间添加间距并填充所需填充值的方法。这不是我想弄清楚的。

我还找到了使用 axs.tick_params(axis='x', pad=100) 在 x 轴标签和 x 轴之间添加间距的方法,这也不是我想要的。

这是我的代码和当前输出,以及我尝试进行的更改的草图(将刻度线从轴上移开)。

axs.set_xlabel("x axis label", fontsize=24, labelpad=100)

带有红色标记的热图显示希望将刻度线移出轴:

Heatmap with desired changes

1 个答案:

答案 0 :(得分:2)

您可以通过获取 xtick Line2D 对象的列表然后手动设置它们的位置来实现。这不是自动解决方案,因为您可能需要调整数字以在您想要的位置获得刻度:

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()

enter image description here