Hướng dẫn how do i save multiple plots in python? - làm cách nào để lưu nhiều ô trong python?

Trước hết kiểm tra nhận dạng. Hy vọng rằng mã của bạn thực sự đọc

for i in range(0:244):
    plt.figure()
    y = numpy.array(Data_EMG[i,:])
    x = pylab.linspace(EMG_start, EMG_stop, Amount_samples)
    plt.xlabel('Time(ms)')
    plt.ylabel('EMG voltage(microV)')
    pylab.plot(x, y)
    pylab.show(block=True)

Tại mỗi lần lặp, bạn hoàn toàn tạo ra một con số mới. Điều đó rất không hiệu quả. Ngoài ra, bạn chỉ vẽ hình dáng của bạn trên màn hình và không thực sự lưu nó. Tốt hơn là

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))

Nên nhanh hơn nhiều.

Nội dung

  • How-to

    • Tại sao tôi có rất nhiều ve, và/hoặc tại sao chúng không đúng thứ tự?

    • Xác định mức độ của các nghệ sĩ trong hình

    • Kiểm tra xem một con số trống chưa

    • Tìm tất cả các đối tượng trong một hình của một loại nhất định

    • Ngăn chặn ticklabels có một phần bù

    • Lưu số liệu trong suốt

    • Lưu nhiều sơ đồ vào một tệp PDF

    • Nỗ chỗ cho nhãn đánh dấu

    • Căn chỉnh các ylabel của tôi trên nhiều ô con

    • Kiểm soát thứ tự vẽ của các yếu tố cốt truyện

    • Làm cho tỷ lệ khung hình cho các lô bằng nhau

    • Vẽ nhiều tỷ lệ trục y

    • Tạo hình ảnh mà không có cửa sổ xuất hiện

    • Làm việc với chủ đề

Tại sao tôi có rất nhiều ve, và/hoặc tại sao chúng không đúng thứ tự?#

Một nguyên nhân phổ biến cho hành vi đánh dấu không mong muốn là truyền một danh sách các chuỗi thay vì các số hoặc đối tượng DateTime. Điều này có thể dễ dàng xảy ra mà không cần thông báo khi đọc trong một tệp văn bản được phân phối bằng dấu phẩy. Matplotlib coi danh sách các chuỗi là các biến phân loại (vẽ các biến phân loại) và theo mặc định đặt một dấu hiệu cho mỗi loại và vẽ chúng theo thứ tự chúng được cung cấp.Plotting categorical variables), and by default puts one tick per category, and plots them in the order in which they are supplied.

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)

(Mã nguồn, PNG)

Hướng dẫn how do i save multiple plots in python? - làm cách nào để lưu nhiều ô trong python?

Giải pháp là chuyển đổi danh sách các chuỗi thành các số hoặc đối tượng DateTime (thường là

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
1 hoặc
from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
2).

Để biết thêm thông tin, xem sửa chữa quá nhiều ve.Fixing too many ticks.

Xác định mức độ của các nghệ sĩ trong hình#

Đôi khi chúng ta muốn biết mức độ của một nghệ sĩ. Các đối tượng matplotlib

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
3 có phương pháp
from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
4 thường sẽ trả về mức độ của nghệ sĩ trong pixel. Tuy nhiên, một số nghệ sĩ, đặc biệt là văn bản, phải được hiển thị ít nhất một lần trước khi mức độ của họ được biết đến. Matplotlib cung cấp
from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
5, nên được gọi trước khi gọi
from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
6.

Kiểm tra xem một con số trống chưa#

Trống rỗng thực sự có thể có nghĩa là những điều khác nhau. Con số có chứa bất kỳ nghệ sĩ nào không? Liệu một con số có trống

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
7 vẫn được tính là trống? Là con số trống rỗng nếu nó được hiển thị màu trắng tinh khiết (có thể có những nghệ sĩ có mặt, nhưng họ có thể ở bên ngoài khu vực vẽ hoặc trong suốt)?

Với mục đích ở đây, chúng tôi định nghĩa trống rỗng là: "Hình không chứa bất kỳ nghệ sĩ nào ngoại trừ đó là bản vá nền." Ngoại lệ cho nền là cần thiết, bởi vì theo mặc định, mỗi hình đều chứa

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
8 vì bản vá nền. Định nghĩa này có thể được kiểm tra thông qua:

def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1

Chúng tôi đã quyết định không bao gồm điều này như một phương thức hình vì đây chỉ là một cách xác định trống và kiểm tra trên chỉ là hiếm khi cần thiết. Thông thường người dùng hoặc chương trình xử lý con số biết nếu họ đã thêm một cái gì đó vào hình.

Kiểm tra xem một con số sẽ khiến trống có thể được kiểm tra một cách đáng tin cậy ngoại trừ bằng cách thực sự kết xuất hình và điều tra kết quả được hiển thị.

Tìm tất cả các đối tượng trong hình của một loại# nhất định

Mỗi nghệ sĩ matplotlib (xem hướng dẫn nghệ sĩ) đều có một phương pháp gọi là

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
9 có thể được sử dụng để tìm kiếm nghệ sĩ đệ quy cho bất kỳ nghệ sĩ nào mà nó có thể chứa đáp ứng một số tiêu chí (ví dụ: khớp với tất cả các trường hợp
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
0 hoặc khớp một số hàm bộ lọc tùy ý). Ví dụ: đoạn trích sau đây tìm thấy mọi đối tượng trong hình có thuộc tính
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
1 và làm cho đối tượng màu xanh:Artist tutorial) has a method called
from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
9 that can be used to recursively search the artist for any artists it may contain that meet some criteria (e.g., match all
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
0 instances or match some arbitrary filter function). For example, the following snippet finds every object in the figure which has a
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
1 property and makes the object blue:

def myfunc(x):
    return hasattr(x, 'set_color')

for o in fig.findobj(myfunc):
    o.set_color('blue')

Bạn cũng có thể lọc trên các phiên bản lớp:

import matplotlib.text as text
for o in fig.findobj(text.Text):
    o.set_fontstyle('italic')

Ngăn chặn Ticklabels có một Offset#

Các định dạng mặc định sẽ sử dụng một phần bù để giảm độ dài của các ticklabels. Để tắt tính năng này trên cơ sở trên mỗi trục:

ax.get_xaxis().get_major_formatter().set_useOffset(False)

Đặt

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
2 (mặc định:
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
3) hoặc sử dụng một định dạng khác. Xem
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
4 để biết chi tiết.

Lưu số liệu trong suốt#

Lệnh

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
5 có đối số từ khóa trong suốt, nếu 'đúng', sẽ làm cho hình nền và trục trục trong suốt khi lưu, nhưng sẽ không ảnh hưởng đến hình ảnh được hiển thị trên màn hình.

Nếu bạn cần điều khiển hạt mịn hơn, ví dụ: bạn không muốn độ trong suốt đầy đủ hoặc bạn cũng muốn ảnh hưởng đến phiên bản hiển thị màn hình, bạn có thể đặt các thuộc tính alpha trực tiếp. Hình có một thể hiện

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
8 gọi là bản vá và các trục có một thể hiện hình chữ nhật gọi là bản vá. Bạn có thể đặt bất kỳ tài sản nào trên chúng trực tiếp (facecolor, edgecolor, linewidth, linestyle, alpha). ví dụ.:

fig = plt.figure()
fig.patch.set_alpha(0.5)
ax = fig.add_subplot(111)
ax.patch.set_alpha(0.5)

Nếu bạn cần tất cả các yếu tố hình trong suốt, hiện tại không có cài đặt alpha toàn cầu, nhưng bạn có thể đặt kênh alpha trên các yếu tố riêng lẻ, ví dụ:

ax.plot(x, y, alpha=0.5)
ax.set_xlabel('volts', alpha=0.5)

Lưu nhiều sơ đồ vào một tệp pdf#

Nhiều định dạng tệp hình ảnh chỉ có thể có một hình ảnh cho mỗi tệp, nhưng một số định dạng hỗ trợ các tệp nhiều trang. Hiện tại, Matplotlib chỉ cung cấp đầu ra nhiều trang cho các tệp PDF, sử dụng các phụ trợ PDF hoặc PGF, thông qua các lớp

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
7 và
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))

ax[0].set_title('Ticks seem out of order / misplaced')
x = ['5', '20', '1', '9']  # strings
y = [5, 20, 1, 9]
ax[0].plot(x, y, 'd')
ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)

ax[1].set_title('Many ticks')
x = [str(xx) for xx in np.arange(100)]  # strings
y = np.arange(100)
ax[1].plot(x, y)
ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
8.

Nhường chỗ cho nhãn đánh dấu#

Theo mặc định, matplotlib sử dụng tỷ lệ phần trăm cố định xung quanh các ô con. Điều này có thể dẫn đến các nhãn chồng chéo hoặc bị cắt ở ranh giới hình. Có nhiều cách để khắc phục điều này:

  • Thích ứng thủ công các tham số Subplot bằng cách sử dụng

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(6, 2))
    
    ax[0].set_title('Ticks seem out of order / misplaced')
    x = ['5', '20', '1', '9']  # strings
    y = [5, 20, 1, 9]
    ax[0].plot(x, y, 'd')
    ax[0].tick_params(axis='x', labelcolor='red', labelsize=14)
    
    ax[1].set_title('Many ticks')
    x = [str(xx) for xx in np.arange(100)]  # strings
    y = np.arange(100)
    ax[1].plot(x, y)
    ax[1].tick_params(axis='x', labelcolor='red', labelsize=14)
    
    9 /
    def is_empty(figure):
        """
        Return whether the figure contains no Artists (other than the default
        background patch).
        """
        contained_artists = figure.get_children()
        return len(contained_artists) <= 1
    
    0.

  • Sử dụng một trong các cơ chế bố cục tự động:

    • Bố cục bị ràng buộc (Hướng dẫn bố cục bị ràng buộc)Constrained Layout Guide)

    • Bố cục chặt chẽ (Hướng dẫn bố trí chặt chẽ)Tight Layout guide)

  • Tính toán các giá trị tốt từ kích thước của các yếu tố cốt truyện bản thân (điều chỉnh Subplot kiểm soát theo chương trình)Programmatically controlling subplot adjustment)

Căn chỉnh các ylabel của tôi trên nhiều ô con#

Nếu bạn có nhiều ô con trên nhau và dữ liệu y có các thang đo khác nhau, bạn thường có thể nhận được các nhãn ylabel không liên kết theo chiều dọc trên nhiều ô con, có thể không hấp dẫn. Theo mặc định, matplotlib định vị vị trí x của ylabel để nó không chồng chéo bất kỳ loại nào. Bạn có thể ghi đè hành vi mặc định này bằng cách chỉ định tọa độ của nhãn. Ví dụ dưới đây cho thấy hành vi mặc định trong các ô con bên trái và cài đặt thủ công trong các ô con bên phải.

Hướng dẫn how do i save multiple plots in python? - làm cách nào để lưu nhiều ô trong python?

Kiểm soát thứ tự vẽ của các yếu tố cốt truyện#

Thứ tự vẽ của các yếu tố cốt truyện, và do đó các yếu tố nào sẽ ở trên cùng, được xác định bởi thuộc tính

def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1
1. Xem Zorder Demo để biết mô tả chi tiết.Zorder Demo for a detailed description.

Làm cho tỷ lệ khung hình cho các lô bằng#

Thuộc tính trục

def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1
2 kiểm soát tỷ lệ khung hình của các trục. Bạn có thể đặt nó là 'tự động', 'bằng nhau' hoặc một số tỷ lệ kiểm soát tỷ lệ:

ax = fig.add_subplot(111, aspect='equal')

Xem tỷ lệ khung hình trục bằng nhau cho một ví dụ hoàn chỉnh.Equal axis aspect ratio for a complete example.

Vẽ tỷ lệ nhiều trục y#

Một yêu cầu thường xuyên là có hai thang đo cho trục y trái và phải, có thể sử dụng

def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1
3 (hiện tại không được hỗ trợ, mặc dù nó nằm trong danh sách mong muốn). Điều này hoạt động khá tốt, mặc dù có một số điều kỳ quặc khi bạn đang cố gắng tương tác pan và thu phóng, bởi vì cả hai thang đo không nhận được tín hiệu.

Cách tiếp cận sử dụng

def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1
3 (và chị em
def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1
5) để sử dụng 2 trục khác nhau, tắt khung hình chữ nhật trên trục 2 để giữ cho nó không bị che khuất đầu tiên và đặt thủ công các địa điểm và nhãn hiệu. Bạn có thể sử dụng các định dạng và định vị riêng biệt riêng biệt vì hai trục là độc lập.

(Mã nguồn, PNG)

Hướng dẫn how do i save multiple plots in python? - làm cách nào để lưu nhiều ô trong python?

Xem sơ đồ với các thang đo khác nhau cho một ví dụ hoàn chỉnh.Plots with different scales for a complete example.

Tạo hình ảnh mà không có cửa sổ xuất hiện#

Đơn giản chỉ cần gọi

def is_empty(figure):
    """
    Return whether the figure contains no Artists (other than the default
    background patch).
    """
    contained_artists = figure.get_children()
    return len(contained_artists) <= 1
7 và lưu trực tiếp con số vào định dạng mong muốn:

from os import path
data = numpy.array(Data_EMG)                 # convert complete dataset into numpy-array
x = pylab.linspace(EMG_start, EMG_stop, Amount_samples) # doesn´t change in loop anyway

outpath = "path/of/your/folder/"

fig, ax = plt.subplots()        # generate figure with axes
image, = ax.plot(x,data[0])     # initialize plot
ax.xlabel('Time(ms)')
ax.ylabel('EMG voltage(microV)')
plt.draw()
fig.savefig(path.join(outpath,"dataname_0.png")

for i in range(1, len(data)):
    image.set_data(x,data[i])
    plt.draw()
    fig.savefig(path.join(outpath,"dataname_{0}.png".format(i))
0

Làm việc với các chủ đề#

Matplotlib không an toàn cho chủ đề: trên thực tế, có những điều kiện chủng tộc được biết đến ảnh hưởng đến một số nghệ sĩ. Do đó, nếu bạn làm việc với các chủ đề, bạn có trách nhiệm thiết lập các khóa thích hợp để tuần tự hóa quyền truy cập vào các nghệ sĩ matplotlib.

Bạn có thể làm việc trên các số liệu riêng biệt từ các chủ đề riêng biệt. Tuy nhiên, trong trường hợp đó, bạn phải sử dụng một phụ trợ không tương tác (thường là AGG), vì hầu hết các phụ trợ GUI cũng yêu cầu được chạy từ luồng chính.

Làm cách nào để lưu nhiều lô trong một tệp trong Python?

Vẽ dòng thứ hai bằng phương thức Plot (). Khởi tạo một biến, tên tệp, để tạo tệp pdf. Tạo hàm do người dùng xác định Save_Multi_Image () để lưu nhiều hình ảnh trong tệp PDF. Gọi hàm save_multi_image () với tên tệp.Create a user-defined function save_multi_image() to save multiple images in a PDF file. Call the save_multi_image() function with filename.

Làm cách nào để lưu nhiều lô matplotlib?

Chúng ta có thể sử dụng phương thức SaveFig () của lớp PDFPages để lưu nhiều sơ đồ trong một pdf.Các sơ đồ Matplotlib chỉ đơn giản là được lưu dưới dạng các tệp PDF với.Tiện ích mở rộng PDF.use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the . pdf extension.

Làm cách nào để lưu nhiều sơ đồ dưới dạng hình ảnh trong Python?

Lưu một lô trên đĩa của bạn dưới dạng tệp hình ảnh ngay bây giờ nếu bạn muốn lưu các số liệu matplotlib dưới dạng tệp hình ảnh theo chương trình, thì tất cả những gì bạn cần là matplotlib.pyplot.hàm saveFig ().Chỉ cần chuyển tên tệp mong muốn (và thậm chí vị trí) và hình sẽ được lưu trữ trên đĩa của bạn.matplotlib. pyplot. savefig() function. Simply pass the desired filename (and even location) and the figure will be stored on your disk.

Làm thế nào để bạn thực hiện nhiều lô trong Python?

Để tạo nhiều lô, sử dụng phương thức matplotlib.pyplot.subplots trả về hình cùng với đối tượng trục hoặc mảng của đối tượng trục.Các thuộc tính NCOLS của phương thức Subplots () Xác định số lượng hàng và cột của lưới Subplot.use matplotlib. pyplot. subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.