Combining Timeseries Dual Plot Axis

I am trying to combine two timeseries graphs. One is a boxplot and one is a line. The same x axis would be used for the both and the left y-axis is called “Midday Stem Water Potential” and the right y-axis is called “Cumulative Applied Irrigation”. They both graph fine on their own (see examples) but am having issues with the x-axis when they are combined. The boxplot seems to get smashed and the x axis no longer starts on 4/1/24. Any ideas?

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Load your data from an Excel file
file_path = '/Users/ajgal/Documents/applied_irrigation.xlsx'
sheet_name = 'Sheet1'  # Update if your sheet has a different name
irr = pd.read_excel(file_path, sheet_name=sheet_name)

# Ensure that 'Event' is a datetime column for proper date formatting
irr['Event'] = pd.to_datetime(irr['Event'])

# Plotting
fig, ax = plt.subplots(figsize=(22, 9))

# Plot the first line
color1 = 'orange'
ax.set_xlabel(' ', fontsize=20)  # Increase the font size of the x-axis label
ax.set_ylabel('Cumulative Applied Irrigation (mm)', color='black', fontsize=20)  # Increase the font size of the y-axis label
ax.plot(irr['Event'], irr['B4N_mm_cum'], color=color1, label='DRI', linewidth=2)
ax.tick_params(axis='y', labelcolor=color1, labelsize=16)  # Increase the font size of y-axis ticks

# Plot the second line
color2 = 'darkblue'
ax.plot(irr['Event'], irr['B4S_mm_cum'], color=color2, label='Micro Drip', linewidth=2)
ax.tick_params(axis='y', labelcolor='black', labelsize=16)  # Ensure tick labels are black and larger

# Set axis line and ticks to black
ax.spines['left'].set_color('black')
ax.spines['left'].set_linewidth(0.5)
ax.yaxis.set_tick_params(color='black', size=6, width=0.5)

# Customize x-axis date labels
ax.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%m-%d'))  # Format dates (adjust as needed)
ax.xaxis.set_major_locator(plt.matplotlib.dates.AutoDateLocator())  # Automatically adjust date ticks
ax.tick_params(axis='x', labelsize=16)  # Increase the font size of x-axis date labels

# Add grid lines and title
ax.grid(False)
plt.title('', fontsize=20)  # Increase the font size of the title

# Add a legend at the bottom
plt.legend(loc=1, prop={'size': 20})

# Save the plot
#plt.savefig('/path/to/save/your_plot.png', bbox_inches='tight', transparent=True)
plt.show()

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates

# Load your data from Excel files
file_path_irrigation = '/Users/ajgal/Documents/applied_irrigation.xlsx'
file_path_swp = '/Users/ajgal/Documents/combined_SWP_2024.xlsx'

# Read irrigation data
irr = pd.read_excel(file_path_irrigation)

# Read SWP data
SWP = pd.read_excel(file_path_swp)
SWP['Sampling'] = pd.to_datetime(SWP['Sampling'], format='%Y-%m-%d')
SWP['reading_bar'] = SWP['reading_bar'] / 10
SWP['Sampling'] =  pd.to_datetime(SWP['Sampling'])
SWP.sort_values('Sampling', inplace=True)
SWP['Sampling'] = SWP['Sampling'].dt.strftime('%m-%d')

# Plotting
fig, ax1 = plt.subplots(figsize=(22, 9))

# Plot the SWP data on the primary y-axis
color_DRI = 'orange'
color_drip = 'darkblue'
ax1.set_ylim(-2, 0)  # Set the limits for the primary y-axis
ax1.tick_params(axis='y', labelcolor='black', labelsize=16)

# Plot the boxplot for SWP data
sns.boxplot(x=SWP['Sampling'], y=SWP['reading_bar'], hue=SWP['block'], palette={'DRI': color_DRI, 'Micro Drip': color_drip}, width=0.7, ax=ax1)

# Format the x-axis to show only dates in 'm-d' format
ax1.tick_params(axis='x', labelsize=16)  # Increase the font size of x-axis date labels

# Add grid lines and title
ax1.grid(False)
plt.title('', fontsize=20)  # Increase the font size of the title
plt.ylabel("Midday Stem Water Potential (MPa)", color='black', fontsize=20)
plt.xlabel(" ")
plt.legend(loc=1, prop={'size': 20})

# Show the plot
plt.show()

but putting them together yields this with a wonky x-axis:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as mdates

# Load your data from Excel files
file_path_irrigation = '/Users/ajgal/Documents/applied_irrigation.xlsx'
file_path_swp = '/Users/ajgal/Documents/combined_SWP_2024.xlsx'

# Read irrigation data
irr = pd.read_excel(file_path_irrigation, sheet_name='Sheet1')
irr['Event'] = pd.to_datetime(irr['Event'], format='%Y-%m-%d')
irr.sort_values('Event', inplace=True)
irr['Event'] = irr['Event'].dt.strftime('%m-%d')

# Read SWP data
SWP = pd.read_excel(file_path_swp)
SWP['reading_bar'] = SWP['reading_bar'] / 10
SWP['Sampling'] = pd.to_datetime(SWP['Sampling'], format='%Y-%m-%d')
SWP.sort_values('Sampling', inplace=True)
SWP['Sampling'] = SWP['Sampling'].dt.strftime('%m-%d')

# Plotting
fig, ax1 = plt.subplots(figsize=(22, 9))

# Plot the SWP data on the primary y-axis
color_DRI = 'orange'
color_drip = 'darkblue'
ax1.set_ylim(-2, 0)  # Set the limits for the primary y-axis
ax1.tick_params(axis='y', labelcolor='black', labelsize=16)

# Plot the boxplot for SWP data
sns.boxplot(x=SWP['Sampling'], y=SWP['reading_bar'], hue=SWP['block'], palette={'DRI': color_DRI, 'Micro Drip': color_drip}, width=0.7, ax=ax1)

# Format the x-axis for the first y-axis
ax1.tick_params(axis='x', labelsize=16)  # Increase the font size of x-axis date labels
plt.xticks(rotation=45)
plt.xlabel('')

# Set the y-axis label for the primary y-axis
ax1.set_ylabel("Midday Stem Water Potential (MPa)", color='black', fontsize=20)

# Add a legend for the SWP data
handles, labels = ax1.get_legend_handles_labels()
ax1.legend(handles, labels, loc=2, prop={'size': 16})

# Create a secondary y-axis
ax2 = ax1.twinx()

# Plot the irrigation data on the secondary y-axis
ax2.set_xlabel(' ', fontsize=20)  # Increase the font size of the x-axis label
ax2.set_ylabel('Cumulative Applied Irrigation (mm)', color='black', fontsize=20)  # Increase the font size of the y-axis label
ax2.plot(irr['Event'], irr['B4N_mm_cum'], color=color_DRI, label='DRI', linewidth=2)
ax2.plot(irr['Event'], irr['B4S_mm_cum'], color=color_, label='Micro Drip', linewidth=2)
ax2.tick_params(axis='y', labelcolor='black', labelsize=16)  # Ensure tick labels are black and larger

# Set axis line and ticks to black
ax2.spines['right'].set_color('black')
ax2.spines['right'].set_linewidth(0.5)
ax2.yaxis.set_tick_params(color='black', size=6, width=0.5)

# Customize x-axis date labels
ax2.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))  # Format dates
ax2.xaxis.set_major_locator(mdates.AutoDateLocator())  # Automatically adjust date ticks
ax2.tick_params(axis='x', labelsize=16)  # Increase the font size of x-axis date labels

# Add grid lines and title for the second y-axis
ax2.grid(False)
ax2.set_title('', fontsize=20)  # Increase the font size of the title

# Show the plot
plt.show()

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật