mazz0
mazz0

Reputation: 715

How should width be set for a bar in matplotlib?

I'm using python 2, and the following code is just using some example data, my actual data can be of varying lengths and might not be minutely.

  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()

How am I supposed to set the width of the bars automatically? As it is I get the following:

no width set[1]

If I set the width to 0.0006 then it looks good for the example data:

width manually set to 0.0006[2]

from which I've worked out that matplotlib is measuring the x axis in days (since 0.0007 days is almost exactly 1 minute, which matches my time intervals, and 0.0006 gives the gaps between bars) but that's no good if I get hourly values or seconds, or weeks, etc. Surely there's an option for handling this automatically?

Upvotes: 7

Views: 3341

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339775

If you want the bar width to be no larger than the difference between any successive datetimes, you can calculate that number and supply it to the bar's width argument.

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

Upvotes: 11

Related Questions