0

I have a plot that is an overlay of a boxplot and a scatter plot (red data points). Everything is fine except that the red data points are not lining up on the x axis with the boxplot x axis. I think this is because two different plot methods are used on the same axis?? I have noticed that the second method plot of "scatter" effectively shifts the boxplots to the right on the x axis. Plotting the boxplot without the scatter plot does not shift the x axis values as shown below. The method i'm using below should work but it is not. Here is my code:

sitenames = df3.plant_name.unique().tolist()
months = ['JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER']
from datetime import datetime
monthn = datetime.now().month
newList = list()
for i in range(monthn-1):
    newList.append(months[(monthn-1+i)%12])
print(newList)
for i, month in  enumerate(newList,1):
    #plt.figure()
    fig, ax = plt.subplots()
    ax = df3[df3['month']==i].boxplot(by='plant_name',column='Var')
    df3c[df3c['month']==i].plot(kind='scatter', x='plant_name', y='Var',ax=ax,color='r',label='CY')
    plt.xticks(rotation=90, ha='right')
    plt.suptitle('1991-2020 ERA5 WIND PRODUCTION',y=1)
    plt.title(months[i-1])
    plt.xlabel('SITE')
    plt.ylabel('VARIABILITY')
    plt.legend()
    plt.show()

Here is the plot from "February" that shows the mis-aligned x axis:

enter image description here

Here are partial rows for df3, df3c:

df3.head(3)
Out[223]: 
  plant_name  month  year     power_kwh  power_kwh_rhs   Var
0  BII NEE STIPA      1  1991  11905.826075   14673.281223 -18.9
1  BII NEE STIPA      1  1992  14273.927688   14673.281223  -2.7
2  BII NEE STIPA      1  1993  12559.828360   14673.281223 -14.4

df3c.head(3)
Out[224]: 
  plant_name  month    year     power_kwh  power_kwh_rhs   Var
0  BII NEE STIPA      1  2021.0  14863.643952   14673.281223   1.3
1  BII NEE STIPA      2  2021.0   9663.393155   12388.328084 -22.0
2  DOS ARBOLITOS      1  2021.0  36819.502285   36882.205762  -0.2

I have found a similar problem but can't see how to insert this solution to my code: Shift matplotlib axes to match eachother

user2100039
  • 1,280
  • 2
  • 16
  • 31

0 Answers0