In this video a detailed description of how we can plot a bar plot of data in primary and secondary axis using python.
Previous videos:
1. Clip raster in Python
• How to Clip rasters in Python
2. How to download DEM data | SRTM 90m data
• How to download DEM data | SRTM 90m data
3. How to plot Shapefile in Python | Part-03
• How to plot Shapefile in Python | Part-03
4. How to plot Shapefile in Python | Part-02
• How to plot Shapefile in Python | Part-02
5. How to plot Shapefile in Python | Part-01
• How to plot Shapefile in Python | Part-01
##code
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df_rainfall = pd.read_excel('path to rainfall data')
df_slope = pd.read_excel('path to slope data')
Assuming both DataFrames have the same length
If not, you may need to interpolate or align them accordingly
df_combined = pd.concat([df_rainfall['cumulative distance'], df_rainfall['Rainfall'], df_slope['slope']], axis=1)
Get the number of data points
num_data_points = len(df_combined)
Plotting
fig, ax1 = plt.subplots(figsize=(12, 7))
# Plotting bar plot with index vs rainfall on primary y-axis
ax1.bar(np.arange(num_data_points), df_combined['Rainfall'].values, color='tab:blue', label='Rainfall')
ax1.set_xlabel('Number of points', fontsize=16) # Change x-axis label
ax1.set_ylabel('Rainfall (mm)', color='tab:blue', fontsize=16)
ax1.tick_params(axis='y', labelcolor='tab:blue', labelsize=14)
ax1.set_ylim(0, 180)
Adjust tick sizes of x-axis
ax1.tick_params(axis='x', labelsize=14)
ax1.grid(True)
Create a secondary y-axis for slope
ax2 = ax1.twinx()
# Plotting bar plot with index vs slope on secondary y-axis
ax2.bar(np.arange(num_data_points), df_combined['slope'].values, color='tab:orange', label='Slope')
ax2.set_ylabel('Slope (m/m)',color='tab:orange', fontsize=16)
ax2.tick_params(axis='y', labelcolor='tab:orange', labelsize=14)
Set the limits of the secondary y-axis
ax2.set_ylim(0, 0.2) # Adjust the limits as needed
# Reverse the secondary y-axis
ax2.set_ylim(ax2.get_ylim()[::-1])
plt.title('Rainfall vs Slope ', fontsize=20)
plt.savefig('path to save figure')
plt.show()
On this page of the site you can watch the video online How to plot data on primary and inverted secondary axis using python with a duration of hours minute second in good quality, which was uploaded by the user My Knowlege space 05 May 2024, share the link with friends and acquaintances, this video has already been watched 192 times on youtube and it was liked by 6 viewers. Enjoy your viewing!