Home > Enterprise >  Boxplot and Barchart shifted when using matplotlib
Boxplot and Barchart shifted when using matplotlib

Time:07-19

I'm trying to align a barplot and a boxplot but when I do so, the boxplot is basically shifted along the x-axis. This is my previous code:

d = {"1":[140,118], "2":[133,111], "3":[111, 86]}
df = pd.DataFrame(data=d)
x = df["1"]
y = df["2"]
z = df["3"]
columns =[x, y, z]
l=["top", "middle", "bottom"]
ice_val = [140, 133, 111]
withoutice_val = [118, 111, 86]

x = np.arange(len(l))
width = 0.35

fig, ax = plt.subplots()
r1 = ax.bar (x - width/2, ice_val, width, label="with ice-activity")
r2 = ax.bar (x   width/2, withoutice_val, width, label="without ice-activity")
ax1=ax.twinx()
ax1.boxplot(columns)
ax1.set_ylim(ax.get_ylim())
ax.set_xticks(x)

plt.show()

which gives me this result:

resulting plotpng

There are already some questions with the same problem, but those answers seem to somehow not solve my problem (or I'm simply not experienced enough with Python)..

I really appreciate any help! Thanks!!

CodePudding user response:

np.arange 

starts at 0, you can do

x = 1   np.arange(len(l))
  • Related