如何在matplotlib中设置条的宽度?

时间:2018-11-08 13:57:07

标签: matplotlib

我正在使用python 2,下面的代码仅使用了一些示例数据,我的实际数据长度可能有所不同,可能不是很细致。

  import numpy as np
  import datetime  
  import matplotlib
  import matplotlib.pyplot as plt  

  fig, ax = plt.subplots()  

  x_values = [datetime.datetime(2018, 11, 8, 11, 16), 
    datetime.datetime(2018, 11, 8, 11, 17), 
    datetime.datetime(2018, 11, 8, 11, 18), 
    datetime.datetime(2018, 11, 8, 11, 19), 
    datetime.datetime(2018, 11, 8, 11, 20), 
    datetime.datetime(2018, 11, 8, 11, 21), 
    datetime.datetime(2018, 11, 8, 11, 22), 
    datetime.datetime(2018, 11, 8, 11, 23), 
    datetime.datetime(2018, 11, 8, 11, 24), 
    datetime.datetime(2018, 11, 8, 11, 25), 
    datetime.datetime(2018, 11, 8, 11, 26), 
    datetime.datetime(2018, 11, 8, 11, 27), 
    datetime.datetime(2018, 11, 8, 11, 28), 
    datetime.datetime(2018, 11, 8, 11, 29), 
    datetime.datetime(2018, 11, 8, 11, 30), 
    datetime.datetime(2018, 11, 8, 11, 31)]
  y_values = [1392.1017964071857,
    1392.2814371257484,
    1392.37125748503,
    1227.6802721088436,
    1083.1,
    1317.0461538461539,
    1393.059880239521,
    1393.4011976047905,
    1393.491017964072,
    1393.8502994011976,
    1318.3461538461538,
    1229.4965986394557,
    1394.2095808383233,
    1394.3892215568862,
    1394.6586826347304,
    1394.688622754491]

  rects1 = ax.bar(x_values, y_values)
  fig.tight_layout()
  plt.show()

我应该如何自动设置条的宽度?就这样,我得到以下信息:

no width set[1]

如果我将宽度设置为0.0006,那么对于示例数据来说看起来不错:

width manually set to 0.0006[2]

从中我得出了matplotlib以天为单位测量x轴的信息(因为0.0007天几乎正好是1分钟,这与我的时间间隔匹配,而0.0006给出了条之间的间隔),但是如果我得到每小时或几秒钟或几周等等。确定有自动处理此选项的选项吗?

1 个答案:

答案 0 :(得分:3)

如果您希望栏的宽度不大于任何连续日期时间之间的差,则可以计算该数字并将其提供给栏的width参数。

import matplotlib.dates as mdates 

width = np.min(np.diff(mdates.date2num(x_values)))
ax.bar(x_values, y_values, width=width, ec="k")

enter image description here