2

I'm trying to plot two datasets into one plot with matplotlib. One of the two plots is misaligned by 1 on the x-axis. This MWE pretty much sums up the problem. What do I have to adjust to bring the box-plot further to the left?

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

titles = ["nlnd", "nlmd", "nlhd", "mlnd", "mlmd", "mlhd", "hlnd", "hlmd", "hlhd"]
plotData = pd.DataFrame(np.random.rand(25, 9), columns=titles)
failureRates = pd.DataFrame(np.random.rand(9, 1), index=titles)
color = {'boxes': 'DarkGreen', 'whiskers': 'DarkOrange', 'medians': 'DarkBlue', 
         'caps': 'Gray'}
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
plotData.plot.box(ax=ax1, color=color, sym='+')
failureRates.plot(ax=ax2, color='b', legend=False)
ax1.set_ylabel('Seconds')
ax2.set_ylabel('Failure Rate in %')
plt.xlim(-0.7, 8.7)
ax1.set_xticks(range(len(titles)))
ax1.set_xticklabels(titles)
fig.tight_layout()
fig.show()

Actual result. Note that its only 8 box-plots instead of 9 and that they're starting at index 1.

MWE Picture

2 Answers 2

1

The issue is a mismatch between how box() and plot() work - box() starts at x-position 1 and plot() depends on the index of the dataframe (which defaults to starting at 0). There are only 8 plots because the 9th is being cut off since you specify plt.xlim(-0.7, 8.7). There are several easy ways to fix this, as @Sheldore's answer indicates, you can explicitly set the positions for the boxplot. Another way you can do this is to change the indexing of the failureRates dataframe to start at 1 in construction of the dataframe, i.e.

failureRates = pd.DataFrame(np.random.rand(9, 1), index=range(1, len(titles)+1))

note that you need not specify the xticks or the xlim for the question MCVE, but you may need to for your complete code.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You can specify the positions on the x-axis where you want to have the box plots. Since you have 9 boxes, use the following which generates the figure below

plotData.plot.box(ax=ax1, color=color, sym='+', positions=range(9))

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.