如何压缩这些代码行并说,如果我想分别绘制所有3个图,我该如何使用matplotlib子图函数来做到这一点?以下是我所做的,但是不确定如何压缩它:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set()
totalpop = 18000
subpop = [300, 400, 500]
samplesize_list1 = [10, 20, 30] #sample size 60
samplesize_list2 = [40, 50, 60] #sample size 150
samplesize_list3 = [70, 80, 90] #sample size 240
label_list = ['size60', 'size150', 'size240']
std_list = [300, 500, 700]
mean_list = [450, 670, 780]
repeat = 500 #repeated random sampling of 500 sampling outcomes
samplingdist1 = []
for i in range(500):
sample1 = []
for i in range(len(samplesize_list1)):
for j in range(samplesize_list1[i]):
s = 0
while True:
s = np.random.normal(mean_list[i], std_list[i], 1).tolist()
if s[0] > 0:
break
sample1 += s
samplingdist1.append(np.median(sample1))
sns.distplot(samplingdist1, label = 'size60')
samplingdist2 = []
for i in range(500):
sample2 = []
for i in range(len(samplesize_list2)):
for j in range(samplesize_list2[i]):
s = 0
while True:
s = np.random.normal(mean_list[i], std_list[i], 1).tolist()
if s[0] > 0:
break
sample2 += s
samplingdist2.append(np.median(sample2))
sns.distplot(samplingdist2, label = 'size150')
samplingdist3 = []
for i in range(500):
sample3 = []
for i in range(len(samplesize_list3)):
for j in range(samplesize_list3[i]):
s = 0
while True:
s = np.random.normal(mean_list[i], std_list[i], 1).tolist()
if s[0] > 0:
break
sample3 += s
samplingdist3.append(np.median(sample3))
sns.distplot(samplingdist3, label = 'size240')
我从中得到的图形被绘制在一个图形中,说我想分别绘制它们并分别标记为“ size60”,“ size150”,“ size240”。我该如何处理?
答案 0 :(得分:0)
这是一个简洁的解决方案,其中添加了简短的说明作为注释
# Put your imports here
totalpop = 18000
subpop = [300, 400, 500]
samplesize_list = [[10, 20, 30], [40, 50, 60],[70, 80, 90]] # 3 lists combined into one
# Your label, std, mean and repeat data here
fig = plt.figure(figsize=(13, 3))
axes = fig.subplots(nrows=1, ncols=3) # Create a figure with 3 columns and 1 row
for ind, ax in enumerate(axes.flatten()): # Enumerate here to access index for samplesize
samplingdist = []
for i in range(500):
sample = []
for i in range(len(samplesize_list[ind])): # ind accesses the corresponding sublist
for j in range(samplesize_list[ind][i]):
s = 0
while True:
s = np.random.normal(mean_list[i], std_list[i], 1).tolist()
if s[0] > 0:
break
sample += s
samplingdist.append(np.median(sample))
sns.distplot(samplingdist, label = label_list[ind], ax=ax) # Pass the subplot ax for plotting
ax.legend() # Show the legend
输出