【问题标题】:pandas plot xticks on x-axispandas 在 x 轴上绘制 xticks
【发布时间】:2015-07-10 04:07:11
【问题描述】:

我有一个工作代码,可以在图表中将熊猫数据框显示为 2 个折线图。我还有一个数据框,可以在同一张图表上显示条形图。对于 2 个数据框,我有 x 轴的日期。因为这两个数据框都有日期,所以我的轴最终只有整数 (1,2,3,4,5,6...) 而不是日期。

我认为这条线 df1 = df.set_index(['date']) 已经指定了我想要的 x 轴,当我不在图表上绘制条形图时,日期显示得很好,但是当我绘制条形图时,整数显示而是在轴上。

我的 2 个数据框:

df1:
date      line1  line2
2015-01-01 15.00  23.00
2015-02-01 18.00  10.00

df2:
date      quant  
2015-01-01 500 
2015-02-01 600

我的代码:

df1 =pd.DataFrame(result, columns =[ 'date','line1', 'line2']) 
df1 = df.set_index(['date'])

df2 =pd.DataFrame(quantity, columns =[ 'quant','date']) 
fig = plt.figure()
ax = fig.add_subplot(111)
ax2=ax.twinx()
ax.set_ylim(0,100)
ax2.set_ylim(0,2100)

df1.line1.plot( color = 'red', ax = ax)
df1.line2.plot( color = 'blue', ax = ax)
df2.["quant"].plot(kind = 'bar', ax =ax2, width =0.4)
plt.show()

df1:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 12 entries, 0 to 11
Data columns (total 3 columns):
date        12 non-null object
line1    12 non-null float64
line2     12 non-null float64
dtypes: float64(2), object(1)
memory usage: 384.0+ bytes
None

df2
<class 'pandas.core.frame.DataFrame'>
Int64Index: 11 entries, 0 to 10
Data columns (total 2 columns):
quant         11 non-null int64
date    11 non-null object
dtypes: int64(1), object(1)
memory usage: 264.0+ bytes
None

【问题讨论】:

    标签: python pandas matplotlib plot dataframe


    【解决方案1】:

    您可以只使用ax.plot(df1.date, df1.line1)matplotlib.pyplot 会自动处理日期。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    # your data
    # ===================================
    np.random.seed(0)
    df1 = pd.DataFrame(dict(date=pd.date_range('2015-01-01', periods=12, freq='MS'), line1=np.random.randint(10, 30, 12), line2=np.random.randint(20, 25, 12)))
    
    Out[64]: 
             date  line1  line2
    0  2015-01-01     22     22
    1  2015-02-01     25     21
    2  2015-03-01     10     20
    3  2015-04-01     13     21
    4  2015-05-01     13     21
    5  2015-06-01     17     20
    6  2015-07-01     19     21
    7  2015-08-01     29     24
    8  2015-09-01     28     23
    9  2015-10-01     14     20
    10 2015-11-01     16     23
    11 2015-12-01     22     20
    
    
    
    df2 = pd.DataFrame(dict(date=pd.date_range('2015-01-01', periods=12, freq='MS'), quant=100*np.random.randint(3, 10, 12)))
    
    Out[66]: 
             date  quant
    0  2015-01-01    500
    1  2015-02-01    600
    2  2015-03-01    300
    3  2015-04-01    400
    4  2015-05-01    600
    5  2015-06-01    800
    6  2015-07-01    600
    7  2015-08-01    600
    8  2015-09-01    900
    9  2015-10-01    300
    10 2015-11-01    400
    11 2015-12-01    400
    
    # plotting
    # ===================================
    fig, ax = plt.subplots(figsize=(10, 8))
    ax.plot(df1.date, df1.line1, label='line1', c='r')
    ax.plot(df1.date, df1.line2, label='line2', c='b')
    ax2 = ax.twinx()
    ax2.set_ylabel('quant')
    ax2.bar(df2.date, df2.quant, width=20, alpha=0.1, color='g', label='quant')
    ax.legend(loc='best')
    ax.set_xticks(ax.get_xticks()[::2])
    

    跟进(更新):

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    
    # your data
    # ===================================
    np.random.seed(0)
    df1 = pd.DataFrame(dict(date=pd.date_range('2015-01-01', periods=12, freq='MS'), line1=np.random.randint(10, 30, 12), line2=np.random.randint(20, 25, 12))).set_index('date')
    df2 = pd.DataFrame(dict(date=pd.date_range('2015-01-01', periods=12, freq='MS'), quant=100*np.random.randint(3, 10, 12))).set_index('date')
    df2 = df2.drop(df2.index[4])
    print(df1)
    print(df2)
                line1  line2
    date                    
    2015-01-01     22     22
    2015-02-01     25     21
    2015-03-01     10     20
    2015-04-01     13     21
    2015-05-01     13     21
    2015-06-01     17     20
    2015-07-01     19     21
    2015-08-01     29     24
    2015-09-01     28     23
    2015-10-01     14     20
    2015-11-01     16     23
    2015-12-01     22     20
                quant
    date             
    2015-01-01    500
    2015-02-01    600
    2015-03-01    300
    2015-04-01    400
    2015-06-01    800
    2015-07-01    600
    2015-08-01    600
    2015-09-01    900
    2015-10-01    300
    2015-11-01    400
    2015-12-01    400
    
    # plotting
    # ===================================
    fig, ax = plt.subplots(figsize=(10, 8))
    ax.plot(df1.index, df1.line1, label='line1', c='r')
    ax.plot(df1.index, df1.line2, label='line2', c='b')
    ax2 = ax.twinx()
    ax2.set_ylabel('quant')
    ax2.bar(df2.index, df2.quant, width=20, alpha=0.1, color='g', label='quant')
    ax.legend(loc='best')
    ax.set_xticks(ax.get_xticks()[::2])
    

    【讨论】:

    • 谢谢,我收到了这个错误:ax.plot(df.date, df.line1, label='before', c='r') ValueError: invalid literal for float(): 2015 -05-01
    • @jxn 哪一行会引发该错误?您是在运行我帖子中的示例代码还是将其应用于您自己的数据集?
    • 对不起,这是我自己的数据集
    • @jxn 也许尝试df2.reindex(df1.index) 填充NaN 以查找缺失的日期,然后进行绘图。如果这不能解决问题,您能否上传您的示例数据文件(dropbox sharelink 或 google 驱动程序),以便我看看可能出了什么问题。
    • 可能是因为我的 df1 在那里多出了一个月(它有 11 个月),而我的 df2 只有 10 个月。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多