pythonmatplotlibplotdata-visualizationmultiple-axes

barh with plot : cannot get different scale for data on secondary x axis


I cannot get two different scales for the plot:

I don't know how to activate the scale of the secondary x axis.

"STK" and "Material" are supposed to be displayed at different scales.
How to display "Material" on it's own scale (0,max) like it was done automatically for "STK"?

I need it to be displayed like on the image below :

the plot with two different scales on x axis I'd like to get

Here's the code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = [['MPP1',400,30],['MPP2',3500,700], ['MPP3',1900,3], ['MPP4',15000,56], ['MPP5',8500,306]]
df = pd.DataFrame(df)
df.columns =['MPP', 'STK', 'Material']

plt.rcdefaults()

fig, ax = plt.subplots(constrained_layout=True)
xdata = df.STK
x2data = df.Material
ydata = df.MPP
y_pos = np.arange(len(ydata))

ax.barh(y_pos, df.STK , label='STK per MPP')
ax.invert_yaxis()


ax.plot(x2data, ydata, label='Material per MPP', color='red')
ax.set_xlabel('STK')
ax.legend()

ax2 = ax.secondary_xaxis('top')
ax2.set_xlabel('Material')

ax2.set_xticks(df.Material)
ax2.set_xticklabels(df.Material)
ax2.set_xlabel(r"Material")

plt.show()

Solution

  • You should create the secondary axis with:

    ax2 = ax.twiny()
    

    and plot your data on it:

    ax2.plot(x2data, ydata, label='Material per MPP', color='red')
    

    Pay attention: ax2.plot, not ax.plot.

    Complete Code

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = [['MPP1',400,30],['MPP2',3500,700], ['MPP3',1900,3], ['MPP4',15000,56], ['MPP5',8500,306]]
    df = pd.DataFrame(df)
    df.columns =['MPP', 'STK', 'Material']
    
    
    plt.rcdefaults()
    
    fig, ax = plt.subplots(constrained_layout=True)
    xdata = df.STK
    x2data = df.Material
    ydata = df.MPP
    y_pos = np.arange(len(ydata))
    
    ax.barh(y_pos, df.STK , label='STK per MPP')
    ax.invert_yaxis()
    ax.set_xlabel('STK')
    leg = plt.legend()
    
    
    ax2 = ax.twiny()
    ax2.plot(x2data, ydata, label='Material per MPP', color='red')
    ax2.set_xlabel('Material')
    leg2 = plt.legend()
    
    plt.legend(leg.get_patches()+leg2.get_lines(),
               [text.get_text() for text in leg.get_texts()+leg2.get_texts()])
    leg.remove()
    
    plt.show()
    

    enter image description here