Crop extra white-space on matplotlib picture

3 hours ago 2
ARTICLE AD BOX

I made a "gauge" image using the following code:

taux = 91 # Plot fig, ax = plt.subplots(figsize=(7.5,5), subplot_kw=dict(polar=True)) ax.set_theta_zero_location("W") # theta=0 at the top ax.set_theta_direction(-1) # theta increasing clockwise ax.set_thetamax(180) # stop at 180 degrees n_bars = 101 rad_x = np.deg2rad(np.linspace(0, 180, n_bars, endpoint=False)) ax.bar(rad_x, width=np.deg2rad(180/n_bars), height=0.5, bottom=2, linewidth=1, edgecolor="white",color="#C8C9C9", align="edge") # axis labels axis_labels = list(range(0,105,10)) theta_labels = np.array([rad_x[i] for i in axis_labels]) label_pos = np.append(theta_labels, np.pi) offset = 2 for loc, val in zip(label_pos, axis_labels): ax.annotate(val, xy=(loc, offset-0.2), size= 15, va= 'center', ha= 'center', color="#757C85") # Pointer ang_r = rad_x[taux] ax.plot([ang_r, ang_r], [0, 2.25], color="black", lw=3) ax.add_patch(Circle((0,0), 0.1, transform=ax.transData._b, color="black")) ax.text(0.5, 0.15, "{}%".format(taux), size=16, ha="center", va="center", transform=ax.transAxes, fontweight="bold") ax.set_axis_off() ax.set_position( [0.1, -0.45, 0.8, 2]) plt.savefig("my_gauge.pdf", bbox_inches="tight", pad_inches=0.05, transparent=True) plt.close()

However, I am getting a quite big "blank" space on top. I believe this is because matplotlib is reserving space for a full donut plot, not just half. But I want all the extra blank space gone. How can I crop it? Any solution is welcome.

I have already tried the following, which didn't work:

plt.autoscale(enable=True, axis="both", tight=True). I also tried with tight=None.

I tried these two lines: ax.set_ylim(0, 2.25) and fig.subplots_adjust(top=0.92, bottom=0.08) instead of this line ax.set_position( [0.1, -0.45, 0.8, 2]).

Read Entire Article