Home >Backend Development >Python Tutorial >How to Plot Multiple Pandas DataFrames in Matplotlib Subplots?
Plotting Multiple DataFrames in Subplots with Pandas and Matplotlib
When working with Pandas DataFrames, it's often necessary to visualize multiple datasets simultaneously. While df.plot() provides a convenient way to plot individual DataFrames, it doesn't offer the ability to combine them into subplots.
Question:
How can we plot multiple Pandas DataFrames in subplots, using Matplotlib or any other Python library?
Answer:
For plotting multiple DataFrames in subplots, we can manually create the subplots using Matplotlib and then use the ax keyword to specify the target subplot for each DataFrame.
Implementation:
import matplotlib.pyplot as plt # Generate some sample data df1 = pd.DataFrame({'a': range(10), 'b': range(10, 20)}) df2 = pd.DataFrame({'c': range(20, 30), 'd': range(30, 40)}) # Create a figure fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True) # Plot dataframes on subplots df1.plot(ax=axes[0,0]) df2.plot(ax=axes[0,1]) # ... (repeat for other DataFrames) # Show the plot plt.show()
In the above example:
The above is the detailed content of How to Plot Multiple Pandas DataFrames in Matplotlib Subplots?. For more information, please follow other related articles on the PHP Chinese website!