Is it normal for a bar plot to take *many* times longer than a line plot?

import matplotlib.pyplot as plt
import timeit
import random

def pbar():
    fig = plt.figure(figsize=(5,2))
    ax = fig.add_axes([0.1,0.1,0.8,0.8])
    x = [x for x in range(0,150)]
    y = [random.randint(10,30) for y in range(0,150)],y)
def pline():
    fig = plt.figure(figsize=(5,2))
    ax = fig.add_axes([0.1,0.1,0.8,0.8])
    x = [x for x in range(0,150)]
    y = [random.randint(10,30) for y in range(0,150)]

timeline = timeit.timeit(pline,number=5)
timebar  = timeit.timeit(pbar,number=5)
print('timebar =',timebar)


timeline= 0.14577969996025786
timebar = 1.1682010000222363

timebar/timeline= 8.013468269866852
  • Is there any way to speed up a bar plot??
  • This is relevant when displaying trade volume on plots with the matplotlib mplfinance package. When the user selects kwarg volume=True, then their plots take 6 to 8 times longer.

I am not surprised. Under the hood plot is using a single Line2D Artists where has bar is creating 150 individual Rectangle Artists.

The path to improving the performance depends on exactly what parts of the rectangle is important to the visualization. If your bars are always the same width (and you can get away with specifying the width in points not data space), I would look at LineCollection. Where as if your bars vary in width (or you need to specify the width in data space) then I would look at PatchCollection.

Thanks Tom. Will give LineCollection a try.

Actually made need to use PatchCollection because in some cases I need the edge of the bar to be a slightly different color than the face. Not sure if Lines have edges that can do that.

You will likely need to use PathCollection or PatchCollection as lines only have one color (they are implemented at the bottom as unfilled stroked paths). That said, depending on how much control you need of the width in data space, you might be able to get away with layering two LineCollections with the same data but different colors and linewidth (which if you are using alpha may require a bit of finesse to get exact colors you want, but if you use alpha the exact ordering gets a bit less important).