如何在 matplotlib 中为条形设置宽度? [英] How should width be set for a bar in matplotlib?

查看:87
本文介绍了如何在 matplotlib 中为条形设置宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

据我计算出matplotlib以天为单位测量x轴(因为0.0007天几乎正好是1分钟,这与我的时间间隔匹配,而0.0006给出了条之间的间隔),但是如果我得到每小时值或秒,或周等.当然有自动处理这个的选项吗?

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?

推荐答案

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

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

这篇关于如何在 matplotlib 中为条形设置宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆