简体   繁体   English

使用 matplotlib 遍历循环并为每次迭代绘制子图

[英]Iterating over a loop and plot subplot for each iterations using matplotlib

I am very new to python and I am stuck at something.我对 python 很陌生,我被困在某事上。 Below is the piece of code which plots two lists against each other :下面是一段代码,它将两个列表相互绘制:

plt.figure(figsize=(24, 16), dpi= 80)
for item in temperature:
  plt.plot(timestamp,item)
plt.legend(final_cities, loc = 'best')
plt.xlabel('Date Time Stamp')
plt.ylabel('Temperature in Kelvin')
plt.show()

timestamp and temperature lists looks like:时间戳和温度列表如下所示:

temperature=[[301.68, 300.71, 299.44, 299.6, 299.95], [306.41, 305.51, 303.36, 301.83, 303.37, 307.39]]
timestamp=['2020-09-22 15:00:00', '2020-09-22 18:00:00', '2020-09-22 21:00:00', '2020-09-23 00:00:00', '2020-09-23 03:00:00']

My code is plotting 2 graphs on top of each other.我的代码正在绘制 2 个相互叠加的图形。 I want to print each plot as a subplot.我想将每个图打印为子图。 How do I do it?我该怎么做? Note: Each subplot will belong to a different country whose details are stored in a different list.注意:每个子图都属于不同的国家,其详细信息存储在不同的列表中。

Is this what you are looking for?这是你想要的?


# data
x_data = [some list]
y_data = [some list]

#  x * y should be >= len(x_data) (the amount of subplots)
fig, axs = plt.subplots(x, y)

# use a counter to get elements from your list you want to plot
c = 0
for i in range(x):
    for j in range(y):
        axs[i][j].plot(x_data[c], y_data[c])
        c += 1

    if c > len(x_data):
        break

plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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