简体   繁体   English

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

[英]Matplotlib multiple Y-axes, xlabels disappear?

I am working with Python 3.x to generate boxplots using matplotlib. 我正在使用Python 3.x使用matplotlib生成箱图。

General: I have a data frame, the contents of which I would like to create in to a box plot. 一般:我有一个数据框,我想在框图中创建的内容。 Problem is, the scales across columns arent consistent; 问题是,列之间的比例不一致; l1 and l2 need to be plotted on separate Y axes from l3:l5. l1和l2需要在l3:l5的不同Y轴上绘制。 The first contains 17 columns, the other two have 1 column each. 第一列包含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)

It isnt pretty, but its also not my full data but the outcome is consistent; 它不漂亮,但它也不是我的完整数据,但结果是一致的; labels of the first two columns are gone and only the final is remaining. 前两列的标签已经消失,只剩下最后一列。

I have tried the set_xticks() and a fair few other calls and I am not able to get anywhere. 我已经尝试了set_xticks()和其他几个调用,我无法到达任何地方。

I do know how to offset the y axes and all that; 我知道如何抵消y轴和所有这些; I am basically hung up on the labeling thing. 我基本上挂了标签的东西。

Try this to set your xaxis ticks: 试试这个来设置你的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'])

Output: 输出:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM