python - barh with plot :无法在辅助 x 轴上获得不同的数据比例
问题描述
我无法为情节获得两种不同的比例:
我不知道如何激活辅助 x 轴的比例。
"STK"
并且"Material"
应该以不同的比例显示。
如何"Material"
像自动完成一样以自己的比例(0,max)显示"STK"
?
我需要它如下图所示:
这是代码:
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()
推荐阅读
- regex - 在 VBA 中使用 regExp 时,for 循环不起作用?
- vue.js - props 在 VUE DEV TOOLS 中一直显示为 $attrs
- python - 我如何让我的班级打印出任何现在的孩子?
- android - 进度条没有出现 - Kotlin
- javascript - 如何定期和自动化地从站点获取数据数据?
- spring-boot - Spring Boot + Kotlin + Gralde 项目上的 vscode
- python - 处理决策树python中的分类列
- google-bigquery - 操作表以使用一列条目来创建新列,并为每列的项目计数
- python - 烧瓶 sqlite3 显示图像
- node.js - 在另一台机器上运行通过 docker-compose 与另一个图像链接的 Docker Image 的正确方法是什么?