首页 > 解决方案 > barh with plot :无法在辅助 x 轴上获得不同的数据比例

问题描述

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

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

"STK"并且"Material"应该以不同的比例显示。
如何"Material"像自动完成一样以自己的比例(0,max)显示"STK"

我需要它如下图所示:

我想在 x 轴上有两个不同比例的图

这是代码:

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

标签: pythonmatplotlibplotdata-visualizationmultiple-axes

解决方案


您应该使用以下命令创建辅助轴:

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

在此处输入图像描述


推荐阅读