简体   繁体   中英

Matplotlib multiple Y-axes, xlabels disappear?

I am working with Python 3.x to generate boxplots using 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. The first contains 17 columns, the other two have 1 column each.

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.

I do know how to offset the y axes and all that; I am basically hung up on the labeling thing.

Try this to set your xaxis ticks:

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:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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