简体   繁体   中英

Matplotlib “savefig” as pdf, text overlay

If i run this code in python:

titles = ctf01[0,1:] 

fig = plt.figure(figsize=(11.69,8.27), dpi=100)

for num in range(len(titles)):

    ax = fig.add_subplot(3,4,num+1)

    ax.plot(ctf03[1:,num+1], ctf0102[:,num], 'ro')

    ax.set_title(titles[num])

plt.tight_layout()

fig.text(0.5, 0.04, 'CTF12', ha='center')

fig.text(0.04, 0.5, 'CTF3', va='center', rotation='vertical')

fig.savefig("example.pdf")

i get this in the pdf file:

在此处输入图片说明

I would like to fix the problem with the "figure title" shown in the red circles. If i set the 0.04 value as an negative value the title runs out of paper.

I also would like to save some space with moving the title of the subplots (green circles) into the diagram. Any idea how i can realize this?

Thanks for help.

try to add before fig.savefig("example.pdf") following line.

plt.tight_layout()

you have it in your script but it should come after text

It looks like you're trying to set the x and y labels for the whole figure, which isn't possible as these can only be set on an Axes object. Fortunately we can work around it by creating an 'invisible' subplot that fills the whole area and set the labels on this.

After plotting your subplots you would create the invisible one with:

label_ax = fig.add_subplot(111, frameon=False)

The frameon argument prevents it from drawing the box that is added by the default style. Then you tell it not to draw tick marks and make the tick labels invisible (we can't just remove them as it will mess up the spacing).

label_ax.tick_params(bottom=False, left=False, labelcolor="none")

Finally, set your labels:

label_ax.set_xlabel("CTF12")
label_ax.set_ylabel("CTF3")

You can adjust the vertical positioning of the plot titles by providing a pad argument to the set_title function. Giving a negative value will push the title into the plot, you'll need trial and error to find the value that works.

Putting it all together (with made-up data):

fig = plt.figure(figsize=(11.69, 8.27), dpi=100)
for i in range(10):
    ax = fig.add_subplot(3, 4, i + 1)
    ax.plot([1, 2, 3, 4, 5], "ro")
    ax.set_title("Plot {}".format(i), pad=-15)

label_ax = fig.add_subplot(111, frameon=False)
label_ax.tick_params(bottom=False, left=False, labelcolor="none")
label_ax.grid(False)  # In case the current style displays a grid.
label_ax.set_xlabel("CTF12")
label_ax.set_ylabel("CTF3")

fig.tight_layout()
fig.savefig("example.pdf")

Which gives: 具有图形轴标签的子图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM