0

I am trying to make a nice bar plot, but run into the following issues:

  1. The horizontal grid lines are in front of the bars, even though I tried all kinds of zorder parameters of ax.grid. How can I get the grid to the back?
  2. The tight layout is not tight. I tried fig.tight_layout() and plt.tight_layout(). How can I crop the picture automatically on all sides?
  3. Is there a way to position the xTick-text, so that each "longText" is aligned with its xTick?
import matplotlib.pyplot as plt

def show_mountains(bins, fortyfive=False):
    fig, ax = plt.subplots()
    ax.grid(axis='y', zorder=-100, linewidth=0.2)
    fig.tight_layout()

    xTicks = list(range(len(bins)))

    if fortyfive:
        plt.xticks(rotation=45)
    ax.set_xticks(xTicks)
    ax.set_xticklabels(["longText"]*len(bins), fontsize=13)
    plt.bar(xTicks, bins, width=0.65, color="#6186f1")
    plt.tight_layout()
    plt.close()


domain_bins = [52, 47, 36, 15, 14, 11, 18]
show_mountains(domain_bins, True)

enter image description here

Alexander Boll
  • 228
  • 1
  • 7
  • 3
    For the grid lines: `ax.set_axisbelow(True)`? Did you experiment with the padding parameters of `plt.tight_layout()`? About the tick label rotation, see [How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?](https://stackoverflow.com/questions/43152502/how-can-i-rotate-xticklabels-in-matplotlib-so-that-the-spacing-between-each-xtic/43153984) – JohanC Aug 20 '20 at 14:09
  • `ax.set_axisbelow(True)` works great! `plt.tight_layout(pad=0, w_pad=0, h_pad=0)` also keeps a really tight layout. Finally: `plt.xticks(rotation=45, ha="right")` gives the perfect alignments! I'll edit this to an answer, if you/someone else didn't start already. – Alexander Boll Aug 20 '20 at 14:20

1 Answers1

2
  1. as @JohanC said in a comment you can use ax.set_axisbelow(True) to display the gridlines behind the bars.

  2. You can adjust the amount of space between the figure and the adge of the subplot using the pad value when calling tight_layout:

    pad float, default: 1.08

    Padding between the figure edge and the edges of subplots, as a fraction of the font size.

  3. You can control the alignment of the tick labels using the horizontalalignment or ha kwarg when you set the xticklabels.

For example:

import matplotlib.pyplot as plt

def show_mountains(bins, fortyfive=False):
    fig, ax = plt.subplots()
    ax.grid(axis='y', zorder=-100, linewidth=0.2)
    fig.tight_layout()

    xTicks = list(range(len(bins)))

    if fortyfive:
        plt.xticks(rotation=45)
    ax.set_xticks(xTicks)
    ax.set_xticklabels(["longText"]*len(bins), fontsize=13, ha='right')

    ax.set_axisbelow(True)

    plt.bar(xTicks, bins, width=0.65, color="#6186f1")
    plt.tight_layout(pad=0.1)

    plt.close()

domain_bins = [52, 47, 36, 15, 14, 11, 18]
show_mountains(domain_bins, True)

Produces this plot:

enter image description here

tmdavison
  • 64,360
  • 12
  • 187
  • 165