1

How do I get different x-axis labels in a subplot when generating it inside a for loop, as such;

attributes = ["attr_with_2_categories", "attr_with_5_categories"]
target = 'Target'
for idx, variable in enumerate(attributes):

    plt.subplot(2, 1, idx+1)
    df_rate = DataSet[[target,variable]].groupby([variable]).mean()
    counts = DataSet[variable].value_counts()
    output = pd.concat((df_rate, counts), axis=1, sort=False)
    output.columns = ["DR", "Counts"]
    labels = np.unique(DataSet[variable])

    ax1 = output["Counts"].plot(kind='bar', width=0.5, color='skyblue', use_index=True)
    plt.ylabel("Count")
    ax1.set_xticklabels(labels, rotation = 45)
    ax2 = plt.twinx(ax1)
    ax2.plot(ax1.get_xticks(),output["DR"], linestyle='-', marker='o', linewidth=3.0)
    plt.ylabel("DR")
    plt.grid(False)
    plt.tight_layout()

plt.show()

The result here is two graphs but both graphs end up with the labels of the last graph that has 5 labels wile the first graph has only 2.

1
  • I tested some more and it seems to be a problem only when plots are arranged vertically. Horizontally aranged, the same problem does not occure. Commented Jul 28, 2018 at 16:10

1 Answer 1

2

You need to set the label to the axis objects. You might also need to tweak the spacing. Below is an example:

import matplotlib.pyplot as plt
import numpy as np
numrows = 3
numcols = 3
fig, ax = plt.subplots(ncols=numcols,nrows=numrows)
counter = 0
angles = np.linspace(0, 2*np.pi,100)
for i in range(numrows):
    for j in range(numcols):
        ax[i][j].plot(np.sin((i+1)*angles), np.cos((j+1)*angles))
        ax[i][j].set_xlabel('(%s,%s)'%(i+1,j+1))
        ax[i][j].set_aspect('equal')
plt.subplots_adjust(hspace=1.0)
plt.show()

subplots example with different x_axis labels

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.