2012-04-03 6 views
5

matplotlibに壊れた縦棒グラフを作成したいと思います。私は後だ結果のより良いアイデアを与えることをmatpltolibで壊れた縦棒グラフを作成するには?

、私は一緒にBalsamiqに例を置く:

enter image description here

私はmatpltolib docsexamplesを見て持っていたが、私は」することができます使用する適切なグラフタイプが見つかったようです。リモートで似ているのはboxplotですが、これは私が必要とするものではありません。

  • グラフィクスプリミティブで手動でグラフを描画する必要はありません。
  • データを必要に応じて整形できます。

PS:別の言語(JavaScriptなど)でこれを行う良いライブラリが分かっている場合は、ポインタにも感謝します。

答えて

8

開始日時と停止日時がいくつかあるようです。

その場合は、barを使ってプロットし、軸が日付であることをmatplotlibに伝えてください。

時刻を取得するには、matplotlibの内部日付形式が各整数がその日の0:00に対応するfloatであるという事実を利用することができます。したがって、時間を得るために、我々はちょうどtimes = dates % 1を行うことができます。例として

(これの90%日付を生成し、操作しているプロットはbarに1つだけの呼び出しである。):サイドノートで

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

def main(): 
    start, stop = dt.datetime(2012,3,1), dt.datetime(2012,4,1) 

    fig, ax = plt.subplots() 
    for color in ['blue', 'red', 'green']: 
     starts, stops = generate_data(start, stop) 
     plot_durations(starts, stops, ax, facecolor=color, alpha=0.5) 
    plt.show() 

def plot_durations(starts, stops, ax=None, **kwargs): 
    if ax is None: 
     ax = plt.gca() 
    # Make the default alignment center, unless specified otherwise 
    kwargs['align'] = kwargs.get('align', 'center') 

    # Convert things to matplotlib's internal date format... 
    starts, stops = mpl.dates.date2num(starts), mpl.dates.date2num(stops) 

    # Break things into start days and start times 
    start_times = starts % 1 
    start_days = starts - start_times 
    durations = stops - starts 
    start_times += int(starts[0]) # So that we have a valid date... 

    # Plot the bars 
    artist = ax.bar(start_days, durations, bottom=start_times, **kwargs) 

    # Tell matplotlib to treat the axes as dates... 
    ax.xaxis_date() 
    ax.yaxis_date() 
    ax.figure.autofmt_xdate() 
    return artist 

def generate_data(start, stop): 
    """Generate some random data...""" 
    # Make a series of events 1 day apart 
    starts = mpl.dates.drange(start, stop, dt.timedelta(days=1)) 

    # Vary the datetimes so that they occur at random times 
    # Remember, 1.0 is equivalent to 1 day in this case... 
    starts += np.random.random(starts.size) 

    # Make some random stopping times... 
    stops = starts + 0.2 * np.random.random(starts.size) 

    # Convert back to datetime objects... 
    return mpl.dates.num2date(starts), mpl.dates.num2date(stops) 

if __name__ == '__main__': 
    main() 

enter image description here

、そのイベントのためにある日から始まり次の日に終わると、y軸が翌日に延長されます。もしあなたが好きなら他の方法でそれを扱うことができますが、これは最も簡単な選択肢だと思います。

+1

これは素晴らしいジョーです!それはまさに私が探していたもので、あなたは素晴らしいコードの例を与えました。ありがとうございました。 – brice

関連する問題