trying to plot two Pivot table in one figure

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()

output coming

print of second subgraph

print of first subgraph with no values in second subgraph

question is why it's printing second subgraph separatly?

2 answers

  • answered 2018-04-17 04:17 fhorrobin

    I find that plt.subplots works best for this type of stuff. I'll give you a simple example and you can generalize it to your code.

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

    This accomplishes the same as what you are wanting but with a more succinct notation and tends to work better, especially for a large number of subplots. For example we could do:

    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()
    

    Instead wich is a bit messier here for just 2 plots but generalizes nicely to a collection of N subplots.

  • answered 2018-04-17 04:17 DavidG

    You have created the subplots, however you are not using them when you are plotting the graph. You need pass the subplots as arguments into the plotting function by doing ax=gh1.

    You code should look like:

    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()