[英]Loop for subplot
我已經處理了好幾天了。 我有一個循環來按月獲取信息。 我嘗試將它們放在一個情節中(子情節 1 = 第 1 個月,子情節 2 = 第 2 個月,依此類推),但是我在每個子情節中都獲得了最后一個月。 我錯過了什么?
我的代碼是:
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
plt.figure(0)
for m in range(1,13):
for i in range(4):
for j in range(3):
ax = plt.subplot2grid((4,3), (i,j))
DF_sub = DF[DF['months'] == m]
out = pd.cut(DF_sub['trip'], bins=[0, 0.25, 0.5, 0.75, 1], include_lowest=True)
out_norm = out.value_counts(sort=False, normalize=True)
ax = out_norm.plot.bar(rot=0, color="b", figsize=(6,4))
plt.xticks([])
plt.title('Month-' + str(m))
plt.show()
您迭代了幾個月(1 到 12 個月),但在每個月內,您再次迭代 i 和 j,這意味着您正在重復一遍又一遍地繪制某些內容。
您可以做的是從 0 到 11 進行迭代,定義每個迭代中繪圖的月份和位置。 先來一些數據:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(123)
DF = pd.DataFrame({"months":np.random.choice(np.arange(1,13),100),
"trip": np.random.uniform(size=100)
})
然后按定義繪制,很可能您不需要標簽:
fig, axs = plt.subplots(4, 3)
fig.tight_layout()
months = np.arange(1,13)
labels= ['bin1','bin2','bin3','bin4']
bins = [0, 0.25, 0.5, 0.75, 1]
for m in range(len(months)):
i = m % 4
j = int(m/4)
DF_sub = DF[DF['months'] == months[m]]
out = pd.cut(DF_sub['trip'], bins=bins,
labels=labels,include_lowest=True)
out_norm = out.value_counts(sort=False, normalize=True)
ax = axs[i,j]
ax.bar(x=labels,height=np.array(out_norm))
ax.title.set_text('Month-' + str(months[m]))
ax.set_xticks([])
plt.show()
一個快速的替代方法是使用 seaborn:
import seaborn as sns
DF['bins'] = pd.cut(DF['trip'], bins=bins,labels=labels,include_lowest=True)
counts = pd.crosstab(DF.months,DF.bins,normalize='index')
counts = counts.unstack().reset_index().rename(columns={0:"value"})
g = sns.FacetGrid(counts, col="months",aspect=.7,col_wrap=3)
g.map(sns.barplot, "bins", "value")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.