Home > Backend Development > Python Tutorial > How to Plot Multiple Pandas DataFrames in Matplotlib Subplots?

How to Plot Multiple Pandas DataFrames in Matplotlib Subplots?

Barbara Streisand
Release: 2024-11-30 08:29:20
Original
769 people have browsed it

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()
Copy after login

In the above example:

  • The sharex=True argument ensures that all subplots share the same x-axis scale.
  • The ax keyword specifies the subplot where each DataFrame will be plotted.
  • The axes array contains subplot axes, which can be accessed by indexing (e.g., axes[0, 0] for the top-left subplot).

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template