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()