Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create broken vertical bar graphs in matplotlib?

I'd like to create a broken vertical bar graph in matplotlib.

To give a better idea of the result I'm after, I put an example together with Balsamiq:

enter image description here

I've had a look at the matpltolib docs and examples but I can't seem to find the appropriate chart type to use. The only thing that looks remotely similar is the boxplot but this isn't what I need.

  • I'd rather not have to draw the graph manually with graphics primitive.
  • I can massage the data into shape as needed.

PS: If you know of a good library that does this in another language (javascript, for example), I'd be grateful for the pointer too.

like image 344
brice Avatar asked Apr 03 '12 16:04

brice


People also ask

How do you create a vertical bar plot in Matplotlib?

Create bars ax.bar () would create vertical bar plots, while ax.barh () would draw horizontal bar plots. We’re using Matplotlib bar, and our chart will have a vertical layout. plt.tight_layout () adjusts subplot params so that subplots are nicely fit in the figure.

What is the difference between a bar plot and bar chart?

The bar plots can be plotted horizontally or vertically. A bar chart describes the comparisons between the discrete categories. One of the axis of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories.

How do you plot multiple bars on a graph in Python?

Plotting the multiple bars using plt.bar () function. To avoid overlapping of bars in each group, the bars are shifted -0.2 units and +0.2 units from the X-axis. The width of the bars of each group is taken as 0.4 units. Finally, the multiple bar charts for both boys and girls are plotted in each group.

What is broken axis in Matplotlib?

In broken axis, all pieces of information are provided in the name itself. The axis which is broken or skipped numbers from number line is known as the Broken axis. Below is given an example of a broken axis in the form of the figure. Plotting of broken axis using Python matplotlib with examples


1 Answers

It sounds like you have a few series of start datetimes and stop datetimes.

In that case, just use bar to plot things, and tell matplotlib that the axes are dates.

To get the times, you can exploit the fact that matplotlib's internal date format is a float where each integer corresponds to 0:00 of that day. Therefore, to get the times, we can just do times = dates % 1.

As an example (90% of this is generating and manipulating dates. The plotting is just a single call to bar.):

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

On a side note, for events that start on one day and end on the next, this will extend the y-axis into the next day. You can handle it in other ways if you prefer, but I think this is the simplest option.

like image 93
Joe Kington Avatar answered Sep 22 '22 00:09

Joe Kington