我有一个熊猫数据框架,如下所示:
df = pd.DataFrame({ 'a_wood' : np.random.randn(100),
'a_grassland' : np.random.randn(100),
'a_settlement' : np.random.randn(100),
'b_wood' : np.random.randn(100),
'b_grassland' : np.random.randn(100),
'b_settlement' : np.random.randn(100)})
我想在一个子图中创建每个数据帧头的数据直方图。
fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
m=0
for i in range(2):
for j in range(3):
df.hist(column = df.columns[m], bins = 12, ax=ax[i,j], figsize=(20, 18))
m+=1
为此,前面的代码运行得很好,但现在我想将每个a和b标题(例如"a_woods“和”b-wood“)组合到一个子图中,这样就只有三个直方图了。我尝试将两列赋值给df.columns[[m,m+3]]
,但这不起作用。我还有一个索引列,它包含像"day_1“这样的字符串,我希望它位于x轴上。有人能帮我吗?
这就是我所走的路。
发布于 2018-08-08 23:07:16
我不知道我是否正确理解了你的问题,但像这样的东西可以将情节结合起来。你可能想稍微玩玩alpha,然后改变头部。
#NOTE that you might want to specify your bins or they wont line up exactly
fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(20, 18))
n = 3
for j in range(n):
df.hist(column=df.columns[j], bins=12, ax=ax[j], alpha=0.5, color='red')
df.hist(column=df.columns[j+n], bins=12, ax=ax[j], alpha=0.5, color='blue')
ax[j].set_title(df.columns[j][2:])
要将它们都绘制在彼此的旁边,请尝试以下命令:
#This example doesnt have the issue with different binsizes within one subplot
fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(20, 18))
n = 3
colors = ['red', 'blue']
axes = ax.flatten()
for i,j in zip(range(n), axes):
j.hist([df.iloc[:,i], df.iloc[:,i+n]], bins=12, color=colors)
j.set_title(df.columns[i][2:])
https://stackoverflow.com/questions/51749208
复制相似问题