HOWTO · Seaborn

旋转 Seaborn 图的轴刻度标签

本教程演示了如何在 Python 中的 seaborn 图的轴上旋转刻度标签

Seaborn 为最终图形提供了许多自定义设置。一个如此小但必不可少的定制是我们可以控制两个轴上的刻度标签。

例如,注意下图的问题。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(
    {
        "Date": [
            "01012019",
            "01022019",
            "01032019",
            "01042019",
            "01052019",
            "01062019",
            "01072019",
            "01082019",
        ],
        "Price": [77, 76, 68, 70, 78, 79, 74, 75],
    }
)
df["Date"] = pd.to_datetime(df["Date"], format="%d%m%Y")

plt.figure(figsize=(15, 8))
ax = sns.barplot(x="Date", y="Price", data=df)

seaborn 旋转标签 1

在上面的代码中,我们为产品价格的时间序列数据绘制了一个图表。如你所见,整个日期绘制在 x 轴上。因此,所有内容都重叠并且难以阅读。

对于这种情况,我们可以在轴上旋转刻度标签。

在本教程中,我们将学习如何在 seaborn 图上旋转此类刻度标签。

使用 set_xticklabels() 函数在 Seaborn 轴上旋转标签

set_xticklabels() 函数设置 x 轴上刻度标签的值。我们可以用它来旋转标签。但是,此函数需要一些标签值才能使用 get_xticklabels() 函数返回默认标签并使用 rotation 参数旋转它们。

下面的代码演示了它的用法。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(
    {
        "Date": [
            "01012019",
            "01022019",
            "01032019",
            "01042019",
            "01052019",
            "01062019",
            "01072019",
            "01082019",
        ],
        "Price": [77, 76, 68, 70, 78, 79, 74, 75],
    }
)
df["Date"] = pd.to_datetime(df["Date"], format="%d%m%Y")

plt.figure(figsize=(15, 8))
ax = sns.barplot(x="Date", y="Price", data=df)
ax.set_xticklabels(ax.get_xticklabels(), rotation=30)

seaborn 旋转标签 2

使用 xticks() 函数在 Seaborn 轴上旋转标签

matplotlib.pyplot.xticks() 函数中的 rotation 参数也可以实现这一点。我们不需要传递任何标签,可以直接使用这个函数中的参数。

例如,

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(
    {
        "Date": [
            "01012019",
            "01022019",
            "01032019",
            "01042019",
            "01052019",
            "01062019",
            "01072019",
            "01082019",
        ],
        "Price": [77, 76, 68, 70, 78, 79, 74, 75],
    }
)
df["Date"] = pd.to_datetime(df["Date"], format="%d%m%Y")

plt.figure(figsize=(15, 8))
ax = sns.barplot(x="Date", y="Price", data=df)
plt.xticks(rotation=45)

seaborn 旋转标签 3

使用 setp() 函数在 Seaborn 轴上旋转标签

由于大多数 seaborn 图返回一个 matplotlib 轴对象,我们可以使用该库中的 setp() 函数。我们将使用 xtick() 函数获取刻度标签值,并使用 setp() 函数的 rotation 参数旋转它们。

请参考以下代码。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame(
    {
        "Date": [
            "01012019",
            "01022019",
            "01032019",
            "01042019",
            "01052019",
            "01062019",
            "01072019",
            "01082019",
        ],
        "Price": [77, 76, 68, 70, 78, 79, 74, 75],
    }
)
df["Date"] = pd.to_datetime(df["Date"], format="%d%m%Y")

plt.figure(figsize=(15, 8))
ax = sns.barplot(x="Date", y="Price", data=df)
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)

seaborn 旋转标签 4