Home > Net >  How to completely remove left and bottom white margins of matplotlib draw?
How to completely remove left and bottom white margins of matplotlib draw?

Time:08-03

import numpy as np
from matplotlib import pyplot as plt

data = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
                 [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
                 [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
                 [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
                 [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
                 [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
                 [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])

plt.figure(figsize=(6, 4))
im = plt.imshow(data, cmap="YlGn")

linewidth = 2

for axis in ['top', 'bottom', 'left', 'right']:
    plt.gca().spines[axis].set_linewidth(linewidth)

plt.gca().set_xticks(np.arange(data.shape[1]   1) - .5, minor=True)
plt.gca().set_yticks(np.arange(data.shape[0]   1) - .5, minor=True)
plt.gca().grid(which="minor", color="black", linewidth=linewidth)
plt.gca().tick_params(which="minor", bottom=False, left=False)

plt.tight_layout()

plt.gca().set_xticks(ticks=[])
plt.gca().set_yticks(ticks=[])

plt.savefig("test.pdf",
            bbox_inches="tight",
            transparent="True",
            pad_inches=1.0/72.0 * linewidth / 2.0)

This code will output the following pdf, but you can see that there are white borders on the left and bottom, so the pdf is not centered after being inserted into LaTex. How to solve this problem?

plt result:

plot

CodePudding user response:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
                 [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
                 [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
                 [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
                 [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
                 [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
                 [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])

plt.figure(figsize=(6, 4))
im = plt.imshow(data, cmap="YlGn")

linewidth = 2

for axis in ['top', 'bottom', 'left', 'right']:
    plt.gca().spines[axis].set_linewidth(linewidth)

plt.gca().set_xticks(np.arange(data.shape[1]   1) - .5, minor=True)
plt.gca().set_yticks(np.arange(data.shape[0]   1) - .5, minor=True)
plt.gca().grid(which="minor", color="black", linewidth=linewidth)
plt.gca().tick_params(which="minor", bottom=False, left=False)

plt.tight_layout()

plt.gca().set_xticks(ticks=[])
plt.gca().set_yticks(ticks=[])

plt.gca().tick_params(axis="both",
                      which="major",
                      left=False,
                      bottom=False,
                      labelleft=False,
                      labelbottom=False)

plt.savefig("test.pdf",
            bbox_inches="tight",
            transparent="True",
            pad_inches=1.0 / 72.0 * linewidth / 2.0)

It was an issue with ticks, solved now.

  • Related