Hướng dẫn python savefig with variable name - python savefig với tên biến

Tôi cần sử dụng "SaveFig" trong Python để lưu âm mưu của từng lần lặp của một vòng lặp và tôi muốn cái tên tôi đặt cho hình chứa một phần theo nghĩa đen và một phần số. Cái này xuất phát từ một mảng hoặc là số liên quan đến chỉ số lặp. Tôi làm một ví dụ đơn giản:

# index.py

from numpy import *
from pylab import *
from matplotlib import *
from matplotlib.pyplot import *
import os

x=arange(0.12,60,0.12).reshape(100,5)
y=sin(x)

i=0

while i<99
  figure()
  a=x[:,i]
  b=y[:,i]
  c=a[0]
  plot(x,y,label='%s%d'%('x=',c))

  savefig(#???#)      #I want the name is: x='a[0]'.png
                      #where 'a[0]' is the value of a[0]

cảm ơn rất nhiều.

Đã hỏi ngày 3 tháng 12 năm 2012 lúc 11:48Dec 3, 2012 at 11:48

Hướng dẫn python savefig with variable name - python savefig với tên biến

Vâng, nó nên chỉ đơn giản là thế này:

savefig(str(a[0]))

Đây là một ví dụ đồ chơi. Làm việc cho tôi.

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')

Đã trả lời ngày 3 tháng 12 năm 2012 lúc 12:11Dec 3, 2012 at 12:11

Hướng dẫn python savefig with variable name - python savefig với tên biến

bluesurferbluesurferblueSurfer

5.40612 Huy hiệu vàng41 Huy hiệu bạc61 Huy hiệu Đồng12 gold badges41 silver badges61 bronze badges

2

Tôi đã có cùng nhu cầu gần đây và tìm ra giải pháp. Tôi sửa đổi mã đã cho và sửa một số lỗi rõ ràng.

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)

Hy vọng nó giúp.

Đã trả lời ngày 18 tháng 2 năm 2016 lúc 2:34Feb 18, 2016 at 2:34

Hướng dẫn python savefig with variable name - python savefig với tên biến

Eric Yangeric YangEric Yang

2.46719 Huy hiệu bạc24 Huy hiệu đồng19 silver badges24 bronze badges

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)
5, bạn có thể sử dụng
from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)
6 để định dạng chuỗi động:

import matplotlib.pyplot as plt

for i in range(99):
    plt.figure()
    a = x[:, i]
    b = y[:, i]
    c = a[0]
    plt.plot(a, b, label=f'x={c}')

    plt.savefig(f'x={c}.png')

Đã trả lời ngày 11 tháng 3 năm 2020 lúc 22:57Mar 11, 2020 at 22:57

Hướng dẫn python savefig with variable name - python savefig với tên biến

Chris Adamschris AdamsChris Adams

17,9K4 Huy hiệu vàng20 Huy hiệu bạc36 Huy hiệu đồng4 gold badges20 silver badges36 bronze badges

Sau đây là 30 ví dụ mã của matplotlib.pyplot.savefig (). Bạn có thể bỏ phiếu cho những người bạn thích hoặc bỏ phiếu cho những người bạn không thích và đi đến dự án gốc hoặc tệp nguồn bằng cách theo các liên kết trên mỗi ví dụ. Bạn cũng có thể muốn kiểm tra tất cả các chức năng/lớp có sẵn của mô -đun matplotlib.pyplot hoặc thử chức năng tìm kiếm.30 code examples of matplotlib.pyplot.savefig(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot, or try the search function

Hướng dẫn python savefig with variable name - python savefig với tên biến
.

Ví dụ 1

def plot_wh_methods():  # from utils.utils import *; plot_wh_methods()
    # Compares the two methods for width-height anchor multiplication
    # https://github.com/ultralytics/yolov3/issues/168
    x = np.arange(-4.0, 4.0, .1)
    ya = np.exp(x)
    yb = torch.sigmoid(torch.from_numpy(x)).numpy() * 2

    fig = plt.figure(figsize=(6, 3), dpi=150)
    plt.plot(x, ya, '.-', label='yolo method')
    plt.plot(x, yb ** 2, '.-', label='^2 power method')
    plt.plot(x, yb ** 2.5, '.-', label='^2.5 power method')
    plt.xlim(left=-4, right=4)
    plt.ylim(bottom=0, top=6)
    plt.xlabel('input')
    plt.ylabel('output')
    plt.legend()
    fig.tight_layout()
    fig.savefig('comparison.png', dpi=200) 

Ví dụ #2

def plot_tsne(self, save_eps=False):
        ''' Plot TSNE figure. Set save_eps=True if you want to save a .eps file.
        '''
        tsne = TSNE(n_components=2, init='pca', random_state=0)
        features = tsne.fit_transform(self.features)
        x_min, x_max = np.min(features, 0), np.max(features, 0)
        data = (features - x_min) / (x_max - x_min)
        del features
        for i in range(data.shape[0]):
            plt.text(data[i, 0], data[i, 1], str(self.labels[i]),
                     color=plt.cm.Set1(self.labels[i] / 10.),
                     fontdict={'weight': 'bold', 'size': 9})
        plt.xticks([])
        plt.yticks([])
        plt.title('T-SNE')
        if save_eps:
            plt.savefig('tsne.eps', dpi=600, format='eps')
        plt.show() 

Ví dụ #3

def plot(PDF, figName, imgpath, show=False, save=True):
    # plot
    output = PDF.get_constraint_value()
    plt.plot(PDF.experimentalDistances,PDF.experimentalPDF, 'ro', label="experimental", markersize=7.5, markevery=1 )
    plt.plot(PDF.shellsCenter, output["pdf"], 'k', linewidth=3.0,  markevery=25, label="total" )

    styleIndex = 0
    for key in output:
        val = output[key]
        if key in ("pdf_total", "pdf"):
            continue
        elif "inter" in key:
            plt.plot(PDF.shellsCenter, val, STYLE[styleIndex], markevery=5, label=key.split('rdf_inter_')[1] )
            styleIndex+=1
    plt.legend(frameon=False, ncol=1)
    # set labels
    plt.title("$\\chi^{2}=%.6f$"%PDF.squaredDeviations, size=20)
    plt.xlabel("$r (\AA)$", size=20)
    plt.ylabel("$g(r)$", size=20)
    # show plot
    if save: plt.savefig(figName)
    if show: plt.show()
    plt.close() 

Ví dụ #4

def plot_alignment(alignment, gs, dir=hp.logdir):
    """Plots the alignment.

    Args:
      alignment: A numpy array with shape of (encoder_steps, decoder_steps)
      gs: (int) global step.
      dir: Output path.
    """
    if not os.path.exists(dir): os.mkdir(dir)

    fig, ax = plt.subplots()
    im = ax.imshow(alignment)

    fig.colorbar(im)
    plt.title('{} Steps'.format(gs))
    plt.savefig('{}/alignment_{}.png'.format(dir, gs), format='png')
    plt.close(fig) 

Ví dụ #5

def plot_images(imgs, targets, paths=None, fname='images.jpg'):
    # Plots training images overlaid with targets
    imgs = imgs.cpu().numpy()
    targets = targets.cpu().numpy()
    # targets = targets[targets[:, 1] == 21]  # plot only one class

    fig = plt.figure(figsize=(10, 10))
    bs, _, h, w = imgs.shape  # batch size, _, height, width
    bs = min(bs, 16)  # limit plot to 16 images
    ns = np.ceil(bs ** 0.5)  # number of subplots

    for i in range(bs):
        boxes = xywh2xyxy(targets[targets[:, 0] == i, 2:6]).T
        boxes[[0, 2]] *= w
        boxes[[1, 3]] *= h
        plt.subplot(ns, ns, i + 1).imshow(imgs[i].transpose(1, 2, 0))
        plt.plot(boxes[[0, 2, 2, 0, 0]], boxes[[1, 1, 3, 3, 1]], '.-')
        plt.axis('off')
        if paths is not None:
            s = Path(paths[i]).name
            plt.title(s[:min(len(s), 40)], fontdict={'size': 8})  # limit to 40 characters
    fig.tight_layout()
    fig.savefig(fname, dpi=200)
    plt.close() 

Ví dụ #6

savefig(str(a[0]))
0

Ví dụ #7

savefig(str(a[0]))
1

Ví dụ #8

savefig(str(a[0]))
2

Ví dụ #9

savefig(str(a[0]))
3

Ví dụ #10

savefig(str(a[0]))
4

Ví dụ #11

savefig(str(a[0]))
5

Ví dụ #12

savefig(str(a[0]))
6

Ví dụ #13

savefig(str(a[0]))
7

Ví dụ #14

savefig(str(a[0]))
8

Ví dụ #15

savefig(str(a[0]))
9

Ví dụ #16

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
0

Ví dụ #17

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
1

Ví dụ #18

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
2

Ví dụ #19

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
3

Ví dụ #20

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
4

Ví dụ #21

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
4

Ví dụ #22

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
4

Ví dụ #23

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
4

Ví dụ #24

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
8

Ví dụ #25

import pylab as pl
import numpy as np

# some data
x = np.arange(10)

pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
9

Ví dụ #26

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)
0

Ví dụ #27

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)
1

Ví dụ #28

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)
2

Ví dụ #29

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)
3

Ví dụ #30

from pylab import *
import matplotlib.pyplot as plt

x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0

while i < 99:
    figure()
    a = x[i, :]                   # change each row instead of column
    b = y[i, :]                   

    i += 1                        # make sure to exit the while loop

    flag = 'x=%s' % str(a[0])     # use the first element of list a as the name
    plot(a, b, label=flag)
    plt.savefig("%s.png" % flag)
4