Search code examples
pythonmatplotlibplotalignmentaxes

Control size of figure and declare axes separately


Goal - To have a custom sized figure, with axis having a cartopy projection.

fig=plt.subplots(figsize=(20,10))
#Supress the ticklabels on the x axis
plt.tick_params(labelbottom=False)
plt.tick_params(labelleft=False) #Otherwise I get a tick_label from 0 to 1 on both axes.

ax=plt.axes(projection=ccrs.PlateCarree()) #This is the projection I want to use.
ax.set_global()
ax.coastlines()
ax.gridlines()
ax.set_xticks(np.arange(-180,180,30), crs=ccrs.PlateCarree())
ax.set_yticks(np.arange(-90,90,30), crs=ccrs.PlateCarree())
ax.set_xticklabels(np.arange(-180,180,30), fontsize=10);
ax.set_yticklabels(np.arange(-90,90,30), fontsize=10);

for i in range(len(geofieldcol)):
    ax.scatter(geofieldcol[i][1],geofieldcol[i][0],s=0.1,transform=ccrs.PlateCarree())
    ax.text(geofieldcol[i][1][0]+1.0,geofieldcol[i][0][0]-8,"Orbit "+str(i+1),rotation=80,
    size=15,fontweight="bold", transform=ccrs.PlateCarree())
    
plt.show()

This program is running fine with this plot Groundtrack

However, we can see that in the left and right boundary, there is some mismatch between fig and axes. How can I make the fig and ax align properly while maintaining a big fig size?

I can't try the fig,ax=fig.subplots(figsize=(20,10)) since I need to declare the ax separately for the projection.

plt.tight_layout() is not helping in this case.


Solution

  • Try setting pad=0 when using plt.tight_layout(). From the docs:

    Parameters:

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

    But this will make you ticks invisible. If you need them, adjust the value according to what you need.

    If you need to change the padding separately for top, right, bottom, and left, try setting pad=0 and changing the definition of rect=[0, 0, 1, 1] to something smaller (e.g. [.05, .05, 1, 1]).