barh with plot:无法在第二个 x 轴上获得不同的数据比例

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

我无法获得两种不同比例的情节:

我不知道如何激活辅助x轴的比例。

"STK""Material" 应该以不同的比例显示。
如何像 "STK"?

一样自动按自己的比例 (0,max) 显示 "Material"

我需要它像下图一样显示:

代码如下:

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

您应该创建辅助轴:

ax2 = ax.twiny()

并在其上绘制数据:

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

注意:ax2.plot,不是ax.plot

完整代码

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