【问题标题】:Add horizontal lines to plot based on sort_values criteria根据 sort_values 标准添加水平线以绘制
【发布时间】:2017-05-16 15:03:44
【问题描述】:

问题:

如何根据下面在top_5 变量中捕获的sort_values 标准向plot 添加水平线。:

数据:

这是 CSV 中 data 的一部分:

这是当前情节。

axnum = today_numBars_slice[['High','Low']].plot()
axnum.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))

这是我要添加到该图中的数据(每行的 HighLow 值):

top_5 = today_numBars_slice[['High','Low','# of Trades']].sort_values(by='# of Trades',ascending=False).head()

top_5

High    Low # of Trades
Timestamp           
2017-01-02 12:55:09.100 164.88  164.84  470
2017-01-02 12:10:12.000 164.90  164.86  465
2017-01-02 12:38:59.000 164.90  164.86  431
2017-01-02 11:54:49.100 164.87  164.83  427
2017-01-02 10:52:26.000 164.60  164.56  332

期望的输出:

这是所需输出的示例,显示了 top_5 中的两行:

【问题讨论】:

    标签: python loops pandas matplotlib lines


    【解决方案1】:

    您可以更快地使用DataFrame.nlargest 顶部5 行,然后使用iterrowsaxhline

    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    
    df = pd.read_csv('for_stack_nums')
    #print (df.head())
    
    top_5 = df[['High','Low','# of Trades']].nlargest(5, '# of Trades')
    print (top_5)
          High     Low  # of Trades
    94  164.88  164.84          470
    90  164.90  164.86          465
    93  164.90  164.86          431
    89  164.87  164.83          427
    65  164.60  164.56          332
    
    axnum = df[['High','Low']].plot()
    axnum.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f')) 
    
    for idx, l in top_5.iterrows():
        plt.axhline(y=l['High'], color='r')
        plt.axhline(y=l['Low'], color='b')
    plt.show()
    

    也不需要子集:

    df = pd.read_csv('for_stack_nums.csv')
    #print (df.head())
    
    axnum = df[['High','Low']].plot()
    axnum.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f')) 
    
    for idx, l in df.nlargest(5, '# of Trades').iterrows():
        plt.axhline(y=l['High'], color='r')
        plt.axhline(y=l['Low'], color='b')
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      pyplot.axhline 会是您要找的吗?

      axnum = today_numBars_slice[['High','Low']].plot()
      axnum.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
      
      top_5 = today_numBars_slice[['High','Low','# of Trades']].sort_values(by='# of Trades',ascending=False).head()
      
      for l in top_5.iterrows():
          plt.axhline(l['high'], color='r')
          plt.axhline(l['low'], color='b')
      
      plt.show();
      

      【讨论】:

      • 感谢您的尝试。我收到以下行类型错误:----> 7 plt.axhline(l['high'], color='r')。说TypeError: string indices must be integers
      猜你喜欢
      • 1970-01-01
      • 2015-09-14
      • 2022-01-26
      • 2018-12-27
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多