Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I limit the border size on a matplotlib graph?

I'm making some pretty big graphs, and the whitespace in the border is taking up a lot of pixels that would be better used by data. It seems that the border grows as the graph grows.

Here are the guts of my graphing code:

        import matplotlib
        from pylab import figure

        fig = figure()
        ax = fig.add_subplot(111)
        ax.plot_date((dates, dates), (highs, lows), '-', color='black')
        ax.plot_date(dates, closes, '-', marker='_', color='black')

        ax.set_title('Title')
        ax.grid(True)
        fig.set_figheight(96)
        fig.set_figwidth(24)

Is there a way to reduce the size of the border? Maybe a setting somewhere that would allow me to keep the border at a constant 2 inches or so?

like image 491
Eric the Red Avatar asked Jul 29 '09 23:07

Eric the Red


People also ask

How do I change the size in Matplotlib?

Import matplotlib. To change the figure size, use figsize argument and set the width and the height of the plot. Next, we define the data coordinates. To plot a bar chart, use the bar() function. To display the chart, use the show() function.

How do I reduce a figure size in Matplotlib?

If you've already got the figure created, say it's 'figure 1' (that's the default one when you're using pyplot), you can use figure(num=1, figsize=(8, 6), ...) to change it's size etc. If you're using pyplot/pylab and show() to create a popup window, you need to call figure(num=1,...)

What does Figsize mean in Matplotlib?

figsize is a tuple of the width and height of the figure in inches, and dpi is the dots-per-inch (pixel per inch).


1 Answers

Since it looks like you're just using a single subplot, you may want to skip add_subplot and go straight to add_axes. This will allow you to give the size of the axes (in figure-relative coordinates), so you can make it as large as you want within the figure. In your case, this would mean your code would look something like

    import matplotlib.pyplot as plt

    fig = plt.figure()

    # add_axes takes [left, bottom, width, height]
    border_width = 0.05
    ax_size = [0+border_width, 0+border_width, 
               1-2*border_width, 1-2*border-width]
    ax = fig.add_axes(ax_size)
    ax.plot_date((dates, dates), (highs, lows), '-', color='black')
    ax.plot_date(dates, closes, '-', marker='_', color='black')

    ax.set_title('Title')
    ax.grid(True)
    fig.set_figheight(96)
    fig.set_figwidth(24)

If you wanted, you could even put the parameters to set_figheight/set_figwidth directly in the figure() call.

like image 106
Tim Whitcomb Avatar answered Nov 07 '22 00:11

Tim Whitcomb