如何使用 python 循环为图形生成标题序列
How to use python loop to generate sequence of titles for figures
如果我想生成一个字符串序列 "layer 1", "layer 2", .... , "layer n"
,用作我的图形的标题,是否有使用循环来完成此任务的简单方法?
谢谢,
简称formatted string literals或"f-strings":
def label_yielder(n):
for i in range(1,n+1):
yield(f"label {i}")
# print them out
for x in label_yielder(5):
print(x)
# store them in a list
labels = [x for x in label_yielder(5)]
当然,如果您已经在使用 for
循环进行绘图,您可以直接在绘图调用中使用 f-string(我假设您正在使用 matplotlib.pyplot
,大多数其他图书馆也应该适用):
import matplotlib.pyplot as plt
from numpy.random import randint
for x in range(5):
data = randint(low=1,high=10, size=(10,))
plt.plot(range(10), data, label=f"label{x+1}")
plt.legend()
如果我想生成一个字符串序列 "layer 1", "layer 2", .... , "layer n"
,用作我的图形的标题,是否有使用循环来完成此任务的简单方法?
谢谢,
简称formatted string literals或"f-strings":
def label_yielder(n):
for i in range(1,n+1):
yield(f"label {i}")
# print them out
for x in label_yielder(5):
print(x)
# store them in a list
labels = [x for x in label_yielder(5)]
当然,如果您已经在使用 for
循环进行绘图,您可以直接在绘图调用中使用 f-string(我假设您正在使用 matplotlib.pyplot
,大多数其他图书馆也应该适用):
import matplotlib.pyplot as plt
from numpy.random import randint
for x in range(5):
data = randint(low=1,high=10, size=(10,))
plt.plot(range(10), data, label=f"label{x+1}")
plt.legend()