简体   繁体   English

matplotlib中的子图创建循环

[英]Subplots in matplotlib creating a loop

I'm new to python and I am trying to create a series of subplots with the only parameter changing being the fill_between parameter for each plot. 我是python的新手,我试图创建一系列子图,唯一的参数更改是每个图的fill_between参数。 Currently I repeat the whole code and change the fill_between for each subplot. 目前,我重复整个代码,并为每个子图更改fill_between。 Is there a more efficient way of creating a loop for the subplots where the only thing that changes is the fill_between? 有没有更有效的方式为子图创建循环,其中唯一改变的是fill_between? Below is an example of the type of plots I am trying to produce. 以下是我尝试制作的样地类型的示例。

import numpy as np
import matplotlib.pyplot as plt
#data
data1 = [11,20,25,80]
data2 = [15,35,50,90]
data3 =[25,36,58,63]
data4=[30,40,68,78]
element = np.arange(4)
fig = plt.figure()
#first plot
ax1 = fig.add_subplot(2,2,1)
phase1 = ax1.plot(data1,color='blue', lw=2)
phase2 = ax1.plot(data2,color='blue', lw=2)
phase3 = ax1.plot(data3,color='green', lw=2)
phase4 = ax1.plot(data4,color='green', lw=2)
plt.xticks(element,('La','Ce','Pr','Nd'))
ax1.fill_between(element,data1,data2,color='grey')
ax1.set_yscale('log')
fig.set_size_inches(10,5)
#second plot
ax2 = fig.add_subplot(2,2,2,sharex=ax1,sharey=ax1)
phase1 = ax2.plot(data1,color='blue', lw=2)
phase2 = ax2.plot(data2,color='blue', lw=2)
phase3 = ax2.plot(data3,color='green', lw=2)
phase4 = ax2.plot(data4,color='green', lw=2)
plt.xticks(element,('La','Ce','Pr','Nd'))
#the fill is the ONLY thing to change
ax2.fill_between(element,data3,data4,color='red')
ax2.set_yscale('log')

plt.show()

I hope this helps 我希望这有帮助

import numpy as np
import matplotlib.pyplot as plt

#data
data1 = [11,20,25,80]
data2 = [15,35,50,90]
data3 = [25,36,58,63]
data4 = [30,40,68,78]
element = np.arange(4)

# data is used to automatize the fill_between argument
data = [[data1,data2],[data3,data4]]

# creating an list of the colors used
cols = ['grey','red']

# creating the figure including all axes
fig,ax = plt.subplots(1,2)

for i,a in enumerate(ax):
    phase1 = a.plot(data1,color='blue', lw=2)
    phase2 = a.plot(data2,color='blue', lw=2)
    phase3 = a.plot(data3,color='green', lw=2)
    phase4 = a.plot(data4,color='green', lw=2)
    a.set_xticks(element)
    a.set_xticklabels(['La','Ce','Pr','Nd'])
    a.fill_between(element,data[i][0],data[i][1],color=cols[i])
    a.set_yscale('log')

fig.set_size_inches(10,5)

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

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