【问题标题】:Combining plt.plot(x,y) with plt.boxplot()结合 plt.plot(x,y) 与 plt.boxplot()
【发布时间】:2011-08-21 18:15:49
【问题描述】:

我正在尝试将普通的 matplotlib.pyplot plt.plot(x,y) 与变量 y 作为变量 x 的函数与箱线图相结合。但是,我只想要x 的某些(可变)位置上的箱线图,但这似乎在 matplotlib 中不起作用?

【问题讨论】:

    标签: python numpy matplotlib plot boxplot


    【解决方案1】:

    这对我有用:

    1. 绘制箱线图
    2. 获取箱线图 x 轴刻度位置
    3. 使用箱线图 x 轴刻度位置作为折线图的 x 轴值
    # Plot Box-plot
    ax.boxplot(data, positions=x, notch=True)
    # Get box-plot x-tick locations
    locs=ax.get_xticks()
    
    # Plot a line between the means of each dataset
    # x-values = box-plot x-tick locations
    # y-values = means
    ax.plot(locs, y, 'b-')
    
    
    

    【讨论】:

      【解决方案2】:

      你想要这样的东西吗? positions kwarg 到 boxplot 允许您将箱线图放置在任意位置。

      import matplotlib.pyplot as plt
      import numpy as np
      
      # Generate some data...
      data = np.random.random((100, 5))
      y = data.mean(axis=0)
      x = np.random.random(y.size) * 10
      x -= x.min()
      x.sort()
      
      # Plot a line between the means of each dataset
      plt.plot(x, y, 'b-')
      
      # Save the default tick positions, so we can reset them...
      locs, labels = plt.xticks() 
      
      plt.boxplot(data, positions=x, notch=True)
      
      # Reset the xtick locations.
      plt.xticks(locs)
      plt.show()
      

      【讨论】:

      • 是的,谢谢,这正是我想要的。我一直试图在箱线图中做类似 plt.plot([x,y]) 的事情,但失败了......似乎误解了 kwarg positions
      • +1 用于展示如何保存 xtick 位置。使用轴时,命令为 locs = ax.get_xticks()ax.set_xticks(locs)
      • 除了我上面的评论之外,实际上还需要添加ax.set_xticklabels(locs) 才能获得正确的标签。
      猜你喜欢
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 2019-12-13
      相关资源
      最近更新 更多