【问题标题】:Measurement length for X and Y-axisX 和 Y 轴的测量长度
【发布时间】:2020-09-30 07:37:21
【问题描述】:

我想知道是否可以更改 pandas 创建的图表的测量里程碑。在我的代码中,X 轴代表时间并按月衡量,但衡量里程碑无处不在。

在下图中,X 轴的里程碑是 2012M012012M062012M112013M042013M09

有什么方法可以选择每个里程碑之间的距离应该多长?例如,让它每年或每半年显示一次?

这是我用于制作图表的函数的代码:

def graph(dataframe):
    graph = dataframe[["Profit"]].plot() 
    graph.set_title('Statistics')
    graph.set_ylabel('Thousand $')
    graph.set_xlabel('Time')
    plt.grid(True)          
    plt.show()

实际的数据框只是一个 Excel 文件,其中包含一堆月份和货币值。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    我认为最直接的方法是使用matplotlib.dates 来格式化轴:

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    def graph(dataframe):
        fig, ax = plt.subplots()
        xfmt = mdates.DateFormatter('%YM%m')            #see https://strftime.org/
        major = mdates.MonthLocator([1,7])              #label only Jan and Jul
    
        graph = dataframe[["Profit"]].plot(ax=ax)       #link plot to the existing axes
        graph.set_title('Statistics')
        graph.set_ylabel('Thousand $')
        graph.set_xlabel('Time')
        graph.xaxis.set_major_locator(major)            #set major locator tick on x-axis
        graph.xaxis.set_major_formatter(xfmt)           #format xtick label
        plt.grid(True)          
        plt.show()
    

    但关键是您需要将日期设置为 Python 的内置 datetime.date(而不是 datetime.datetime);感谢this answer。如果您的日期是 str 或不同类型的日期时间,您将需要转换,但在 SO 和其他地方有很多资源可以做到这一点 like thisthis

    In[0]:
    
    dr = pd.date_range('01-01-2012', '01-01-2014', freq='1MS')
    dr = [pd.to_datetime(date).date() for date in df.index]    #explicitly converting to datetime with .date()
    
    df = pd.DataFrame(index=dr, data={'Profit':np.random.rand(25)})
    type(df.index.[0])
    
    Out[0]:
    datetime.date
    

    调用graph(df) 使用上面的例子得到这个情节:


    只是为了扩展这一点,当索引是 pandas.Timestamp 而不是 datetime.date 时会发生以下情况:

    In[0]:
    dr = pd.date_range('01-01-2012', '01-01-2014', freq='1MS')
    # dr = [pd.to_datetime(date).date() for date in df.index]       #skipping date conversion
    df = pd.DataFrame(index=dr, data={'Profit':np.random.rand(25)})
    
    graph(df)
    
    Out[0]:
    

    x 轴格式不正确:

    但是,如果您愿意直接通过matplotlib 而不是pandaspandas 无论如何都使用matplotlib)创建情节,这可以处理更多类型的日期

    In[0]:
    dr = pd.date_range('01-01-2012', '01-01-2014', freq='1MS')
    # dr = [pd.to_datetime(date).date() for date in df.index]         #skipping date conversion
    df = pd.DataFrame(index=dr, data={'Profit':np.random.rand(25)})
    
    def graph_2(dataframe):
        fig, ax = plt.subplots()
        xfmt = mdates.DateFormatter('%YM%m')
        major = mdates.MonthLocator([1,7])
    
        ax.plot(dataframe.index,dataframe['Profit'], label='Profit')
        ax.set_title('Statistics')
        ax.set_ylabel('Thousand $')
        ax.set_xlabel('Time')
        ax.xaxis.set_major_locator(major)
        ax.xaxis.set_major_formatter(xfmt)
        ax.legend()                          #legend needs to be added
        plt.grid(True)          
        plt.show()
    
    graph_2(df)
    type(df.index[0])
    
    Out[0]:
    
    pandas._libs.tslibs.timestamps.Timestamp
    

    这是工作图:

    【讨论】:

      猜你喜欢
      • 2018-04-08
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 2021-08-18
      相关资源
      最近更新 更多