试图在一个图中绘制两个Pivot表

时间:2018-04-17 04:17:40

标签: python matplotlib plot

fig = plt.figure(figsize=(8,6))
gh1 = fig.add_subplot(121)
temp1.plot(kind='bar')
gh1.set_xlabel('credit_history')
gh1.set_ylabel('count of credit history')
gh1.set_title('Applicants by credit history')
gh2 = fig.add_subplot(122)
temp2.plot(kind='bar')
gh2.set_xlabel('credit_history')
gh2.set_ylabel('Probability of loan by credit history')
gh2.set_title('Probability of getting loan by credit history')
plt.show()

输出

print of second subgraph

print of first subgraph with no values in second subgraph

问题是它为什么分别打印第二个子图?

2 个答案:

答案 0 :(得分:0)

我发现plt.subplots最适合这种类型的东西。我将给你一个简单的例子,你可以将它概括为你的代码。

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,6))
temp1.plot(kind='bar', ax=ax1)
temp2.plot(kind='bar', ax=ax2)
fig.show()

这与你想要的完成相同,但是更简洁的符号并且往往更好地工作,特别是对于大量的子图。例如,我们可以这样做:

fig, ax = plt.subplots(1, 2, figsize=(8,6))
temp1.plot(kind='bar', ax=ax[0])
temp2.plot(kind='bar', ax=ax[1])
fig.show()

相反,这里只有2个情节有点麻烦,但很好地概括了N个子图的集合。

答案 1 :(得分:0)

您已经创建了子图,但是在绘制图形时没有使用它们。您需要通过执行ax=gh1将参数作为参数传递到绘图函数中。

您的代码应如下所示:

fig = plt.figure(figsize=(8,6))

gh1 = fig.add_subplot(121)
temp1.plot(kind='bar', ax=gh1)  # pass in subplot as an argument
gh1.set_xlabel('credit_history')
gh1.set_ylabel('count of credit history')
gh1.set_title('Applicants by credit history')

gh2 = fig.add_subplot(122)
temp2.plot(kind='bar', ax=gh2)  # pass in subplot as an argument
gh2.set_xlabel('credit_history')
gh2.set_ylabel('Probability of loan by credit history')
gh2.set_title('Probability of getting loan by credit history')

plt.show()