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

df = pd.read_excel (r'C:\Users\ZiyuZhang\OneDrive - Bota Biosciences\Programm data\sugar consumption.xlsx' ,
                    sheet_name="Sheet1",
                    index_col=0)
df = df.dropna(how='all').T

plt.figure(figsize=(10,5))
plt.ylim(0, 7)
Timelist=[]
Median=[]
for i in df:
    Timelist.append(str(i))
    Median.append(np.median(df[i].dropna()))

plt.boxplot([df[i].dropna() for i in df],labels=Timelist)
plt.plot(Timelist,Median)

plt.show()

I am trying to draw a boxplot with median line, but the x-aixs of boxplot is not aligned with the line chart, why?

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • 1
    By default, the positions for the box plots start at 1, while the line plot starts at internal position 0. You can do `plt.boxplot([....], labels=Timelist, positions=range(len(Timelist)))` to also start the box plots at position 0. – JohanC Aug 11 '21 at 09:00
  • Thanks, now i can fix it, it helps a lot – Ziyu Zhang Aug 13 '21 at 00:51

0 Answers0