【问题标题】:How to set x ticks for seaborn (python) line plot如何为seaborn(python)线图设置x刻度
【发布时间】:2021-04-08 14:51:19
【问题描述】:

我使用 seaborn 制作了 1960-2014 年的折线图,但 xticks 不正确。我只希望出现间隔(如 1960、1970、1980 等)。如何调整 xticks?我尝试旋转它,但似乎没有用。这是我的代码:

#plot figure using sns
g=sns.relplot(x="Year", y="Indicator_Value",
           data=Emissions_C_df,
           kind="line",
           style="Indicator_Name",
           hue="Indicator_Name",
           )
plt.show()

【问题讨论】:

    标签: python-3.x pandas matplotlib seaborn


    【解决方案1】:

    您可以将matplotlib.ticker 中的MaxNLocator 用于主要刻度(十年),并使用FixedLocator 手动设置特定的次要刻度。

    import seaborn as sns
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FixedLocator, MaxNLocator
    
    a = np.arange(50)
    d = {'Year': 1953+a, 'Indicator_Value': a}
    df = pd.DataFrame(data=d)
    
    g = sns.relplot(x="Year", y="Indicator_Value",
               data=df,
               kind="line")
    ax = plt.gca()
    ax.xaxis.set_major_locator(MaxNLocator(steps=[10]))
    ax.xaxis.set_minor_locator(FixedLocator(range(1960,1970)))
    plt.show()
    

    【讨论】:

    • 我还可以在两者之间添加刻度吗?就像 1960-1970 之间的 9 个刻度?我将它复制到另一行并尝试将其更改为“minor_locator”,但它不起作用。
    • 我更新了答案以包含小刻度。
    猜你喜欢
    • 2019-10-29
    • 1970-01-01
    • 2022-06-10
    • 2018-12-06
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    相关资源
    最近更新 更多