plot categorical variable compared to another categorical variable in Python
<p>What is the best way to plot a categorical variable versus another categorical variable in Python. Imagine we have "males" and "females" and, on the other side, we have "paid" and "unpaid". How can I plot a meaningful and easy-to-interpret figure in python describing the information about males and females and if they paid the loan or not. </p>

<p>This type of stacked bar charts can be used:
<a href="http://i.stack.imgur.com/q9QE5.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/q9QE5.jpg" alt="enter image description here"></a></p>

<hr>

<p>The code for the above stacked barchart:</p>

<pre><code>import pandas as pd
import matplotlib.pyplot as plt

raw_data = {'genders': ['Male', 'Female'],
        'Paid': [40, 60],
        'Unpaid': [60, 40]}

df = pd.DataFrame(raw_data, columns = ['genders', 'Paid', 'Unpaid'])


# Create the general blog and the "subplots" i.e. the bars

f, ax1 = plt.subplots(1, figsize=(12,8))

# Set the bar width
bar_width = 0.75

# positions of the left bar-boundaries
bar_l = [i+1 for i in range(len(df['Paid']))] 

# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(bar_width/2) for i in bar_l] 

# Create a bar plot, in position bar_1
ax1.bar(bar_l, 
        # using the pre_score data
        df['Paid'], 
        # set the width
        width=bar_width,
        # with the label pre score
        label='Paid', 
        # with alpha 0.5
        alpha=0.5, 
        # with color
        color='#F4561D')

# Create a bar plot, in position bar_1
ax1.bar(bar_l, 
        # using the mid_score data
        df['Unpaid'], 
        # set the width
        width=bar_width,
        # with pre_score on the bottom
        bottom=df['Paid'], 
        # with the label mid score
        label='Unpaid', 
        # with alpha 0.5
        alpha=0.5, 
        # with color
        color='#F1911E')


# set the x ticks with names
plt.xticks(tick_pos, df['genders'])

# Set the label and legends
ax1.set_ylabel("Proportion")
ax1.set_xlabel("Genders")
plt.legend(loc='upper left')

# Set a buffer around the edge
plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width])
</code></pre>

python matplotlib plot categorical-data