代码之家  ›  专栏  ›  技术社区  ›  vestland

Matplotlib:如何增加刻度线之间的间距(或减少刻度线的数量)?

  •  0
  • vestland  · 技术社区  · 6 年前

    如何增加勾号之间的间距,如下图所示?

    绘图1:SETUP

    数据集

    时间值
    2010-01 1
    2010-02 2
    2010-03 3
    2010-04 4
    2010-05 5
    2010-06 6
    2010-07 7
    2010-08年8
    2010-09年9
    2010-10 8
    2011-01 7
    2011-02 6
    2011-03 5
    2011-04 4
    2011-05 3
    2011-06 2
    2011-07 1
    2011-08 2
    2011-09 3
    2011-10 4
    2011-11 5
    2011-21 6
    < /代码> 
    
    

    我尝试的内容:

    在帖子中,how to:reduce number of ticks with matplotlib,a user shows how to increase space between ticklabelslike this:。

    尝试1 每个n=5 对于n,枚举中的标签(ax.xaxis.get_TickLabels()): 如果n%每分钟!= 0: 打印(n) label.set_可见(假) < /代码>

    图2:一次尝试

    但正如您所看到的,滴答声保持不变。

    因此,使用该设置,我天真地尝试替换ax.xaxis.get_ketlabels().part withax.get_kticks().,but with no success so far:。

    in:
    对于n,勾选enumerate(ax.get_xticks()):
    如果n%每分钟!= 0:
    勾选。设置“可见”(假)
    
    #out:attributeError:“int”对象没有“set_visible”属性
    < /代码> 
    
    

    ax.tick_参数中似乎没有选项?either.您甚至可以找到padding那里,但是没有关于tick spacing的内容。

    任何其他建议都很好!通常,我会将索引更改为periodindex->code>并使用import matplotlib.dates as mdates->code>格式化轴,但我真的很喜欢这一个更直接的技术。

    以下是简单复制和粘贴的全部内容:

    导入 将matplotlib.pyplot导入为plt 将熊猫作为PD导入 将numpy导入为np #df=pd.read_剪贴板(sep='\\s+') 情节设置 图,ax=plt.子批次()。 最大绘图(df[“时间”]、df[“值”]) PLT.Xticks(旋转=45) 尝试1 每个n=5 对于n,枚举中的标签(ax.xaxis.get_TickLabels()): 如果n%每分钟!= 0: 打印(n) label.set_可见(假) 每一个数=5 #对于n,勾选Enumerate(ax.xaxis.get_ticks()): #如果n%每分钟!= 0: ##打印(N) #勾选。设置“可见”(假) 显示() < /代码> <enter image description here

    数据集

    time value
    2010-01 1
    2010-02 2
    2010-03 3
    2010-04 4
    2010-05 5
    2010-06 6 
    2010-07 7
    2010-08 8
    2010-09 9
    2010-10 8
    2011-01 7
    2011-02 6
    2011-03 5
    2011-04 4
    2011-05 3
    2011-06 2
    2011-07 1
    2011-08 2
    2011-09 3
    2011-10 4
    2011-11 5
    2011-21 6
    

    我试过的:

    在岗位上How to: reduce number of ticks with matplotlib,用户演示如何增加勾号之间的间距。标签这样地:

    # Attempt 1
    every_nth = 5
    for n, label in enumerate(ax.xaxis.get_ticklabels()):
        if n % every_nth != 0:
            #print(n)
            label.set_visible(False)
    

    图2:尝试

    enter image description here

    但正如你所看到的,滴答声仍然保持原样。

    所以使用这个设置,我天真地尝试替换ax.xaxis.get_ticklabels()部分与ax.get_xticks()但是到目前为止还没有成功:

    # in:
    for n, tick in enumerate(ax.get_xticks()):
        if n % every_nth != 0:
            tick.set_visible(False)
    
    # out: AttributeError: 'int' object has no attribute 'set_visible'
    

    似乎没有选择ax.tick_params?要么。你甚至会发现衬垫这里,但没有关于刻度线间距的内容。

    任何其他建议都很好!通常我会把索引改为PeriodIndex并使用格式化轴import matplotlib.dates as mdates但我真的希望这项技术更直接。

    以下是简单复制和粘贴的全部内容:

    #imports
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    # df = pd.read_clipboard(sep='\\s+')
    
    # plot setup
    fig, ax = plt.subplots()
    ax.plot(df['time'], df['value'])
    plt.xticks(rotation=45)
    
    # Attempt 1
    every_nth = 5
    for n, label in enumerate(ax.xaxis.get_ticklabels()):
        if n % every_nth != 0:
            #print(n)
            label.set_visible(False)
    
    #every_nth = 5
    #for n, tick in enumerate(ax.xaxis.get_ticks()):
    #    if n % every_nth != 0:
    #        #print(n)
    #        tick.set_visible(False)
    
    plt.show()
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   ImportanceOfBeingErnest    6 年前

    勾号间距由随后的勾号位置的差异严格确定。Matplotlib通常会自动为您找到好的勾号位置。

    导入matplotlib.pyplot as plt 将熊猫作为PD导入 将numpy导入为np df=pd.dataframe(“时间”:np.arange(“2010-01-01”,“2012-01-01”,dtype=“datetime64[m]”), “value”:np.random.randint(0,10,size=24) 图,ax=plt.子批次()。 最大绘图(df[“时间”]、df[“值”]) plt.setp(ax.get xtickLabels(),rotation=45,ha=“right”)。 显示() < /代码>

    如果您不喜欢这些,您可以通过一个断续器提供定制的。

    导入matplotlib.pyplot as plt 导入matplotlib.dates作为mdates 将熊猫作为PD导入 将numpy导入为np df=pd.dataframe(“时间”:np.arange(“2010-01-01”,“2012-01-01”,dtype=“datetime64[m]”), “value”:np.random.randint(0,10,size=24) 图,ax=plt.子批次()。 最大绘图(df[“时间”]、df[“值”]) ax.xaxis.set_major_locator(mdates.monthlocator((1,7))) ax.xaxis.set主要格式化程序(mdates.dateformater(“%y-%b”)) plt.setp(ax.get xtickLabels(),rotation=45,ha=“right”)。 显示() < /代码>

    如果您真的希望您的日期是分类的,您可以使用 multiplelocator 。例如,每5个类别打勾,

    导入matplotlib.pyplot as plt 将matplotlib.ticker导入为mticker 将熊猫作为PD导入 将numpy导入为np df=pd.dataframe(“时间”:np.arange(“2010-01-01”,“2012-01-01”,dtype=“datetime64[m]”), “value”:np.random.randint(0,10,size=24) df[“时间”]=df[“时间”].dt.strftime('%y-%m') 图,ax=plt.子批次()。 最大绘图(df[“时间”]、df[“值”]) ax.xaxis.set_major_locator(mticker.multiplelocator(5))。 plt.setp(ax.get xtickLabels(),rotation=45,ha=“right”)。 显示() < /代码>

    凯利。

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                       "value" : np.random.randint(0,10,size=24)})
    fig, ax = plt.subplots()
    ax.plot(df['time'], df['value'])
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    
    plt.show()
    

    enter image description here

    如果你不喜欢这些,你可以通过自动售票机提供定制的。

    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                       "value" : np.random.randint(0,10,size=24)})
    fig, ax = plt.subplots()
    ax.plot(df['time'], df['value'])
    ax.xaxis.set_major_locator(mdates.MonthLocator((1,7)))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%b"))
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    
    plt.show()
    

    enter image description here

    如果你真的希望你的约会是分类的,你可以用 MultipleLocator . 例如,每5个类别打勾,

    import matplotlib.pyplot as plt
    import matplotlib.ticker as mticker
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                       "value" : np.random.randint(0,10,size=24)})
    df["time"] = df["time"].dt.strftime('%Y-%m')
    
    fig, ax = plt.subplots()
    ax.plot(df['time'], df['value'])
    ax.xaxis.set_major_locator(mticker.MultipleLocator(5))
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    
    plt.show()
    

    enter image description here