gpt4 book ai didi

python - Matplotlib 多个 Y 轴,xlabels 消失了吗?

转载 作者:行者123 更新时间:2023-11-28 19:00:01 26 4
gpt4 key购买 nike

我正在使用 Python 3.x 使用 matplotlib 生成箱线图。

一般:我有一个数据框,我想将其内容创建到一个箱线图中。问题是,跨列的比例不一致; l1 和 l2 需要绘制在与 l3:l5 不同的 Y 轴上。第一个包含 17 列,另外两个各有 1 列。

l1 = [32107.0,20490.0, 32107.0, 22134.0,31564.0, 32107.0, 22134.0, 20732.0, 20490.0, 28406.0]

l2 = [54.4, 40.2, 54.4, 41.1, 49.4, 54.4, 41.1, 37.0, 40.2, 34.2]

l3 = [4595.0, 2164.0, 4595.0, 3500.0, 3733.0, 4595.0, 3500.0, 3214.0, 2164.0, 3388.0]

l4 = [4868.0, 2289.0, 4868.0, 3652.0, 4128.0, 4868.0, 3652.0, 3418.0, 2289.0, 3980.0]

l5 = [3777.0, 1623.0, 3777.0, 2456.0, 3010.0, 3777.0, 2456.0, 2318.0, 1623.0, 2677.0]

df2 = pd.DataFrame(
{'l1' : l1,
'l2' : l2,
'l3': l3,
'l4' : l4,
'l5' : l5})
fig, ax = plt.subplots(figsize=(5, 3))

ax.boxplot(df2[['l1']].transpose())
ax2 = ax.twinx()
ax2.boxplot(df2['l2'], positions = [2])
ax3 = ax.twinx()
ax3.boxplot(df2['l3'], positions = [3])
ax.set_xlim(0, 7)

它不漂亮,但也不是我的完整数据,但结果是一致的;前两列的标签消失了,只剩下最后一个。

我已经尝试了 set_xticks() 和其他一些调用,但我无法到达任何地方。

我确实知道如何偏移 y 轴等等;我基本上挂断了标签的事情。

最佳答案

试试这个来设置你的 xaxis 刻度:

l1 = [32107.0,20490.0, 32107.0, 22134.0,31564.0, 32107.0, 22134.0, 20732.0, 20490.0, 28406.0]

l2 = [54.4, 40.2, 54.4, 41.1, 49.4, 54.4, 41.1, 37.0, 40.2, 34.2]

l3 = [4595.0, 2164.0, 4595.0, 3500.0, 3733.0, 4595.0, 3500.0, 3214.0, 2164.0, 3388.0]

l4 = [4868.0, 2289.0, 4868.0, 3652.0, 4128.0, 4868.0, 3652.0, 3418.0, 2289.0, 3980.0]

l5 = [3777.0, 1623.0, 3777.0, 2456.0, 3010.0, 3777.0, 2456.0, 2318.0, 1623.0, 2677.0]

df2 = pd.DataFrame(
{'l1' : l1,
'l2' : l2,
'l3': l3,
'l4' : l4,
'l5' : l5})
fig, ax = plt.subplots(figsize=(5, 3))

ax.boxplot(df2[['l1']].transpose())
ax2 = ax.twinx()
ax2.boxplot(df2['l2'], positions = [2])
ax3 = ax.twinx()
# ax3.boxplot(df2[['l3','l4','l5']], positions = [3,4,5])
df2[['l3','l4','l5']].plot.box(positions=[3,4,5], ax=ax3)
ax.set_xlim(0, 7)
_ = ax3.xaxis.set_ticks([1,2,3,4,5])
_ = ax3.xaxis.set_ticklabels(['l1','l2','l3','l4','l5'])

输出:

enter image description here

关于python - Matplotlib 多个 Y 轴,xlabels 消失了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53714734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com