How to Plot Pandas DataFrame in Matplotlib: Simple Guide
You can plot a pandas DataFrame in
matplotlib by calling the DataFrame's plot() method, which uses matplotlib under the hood. Simply import matplotlib, create or load your DataFrame, then call df.plot() followed by plt.show() to display the plot.Syntax
The basic syntax to plot a pandas DataFrame using matplotlib is:
df.plot(): This creates the plot from the DataFrame.plt.show(): This displays the plot window.
You can customize the plot type by passing kind parameter like kind='line', kind='bar', etc.
python
import matplotlib.pyplot as plt import pandas as pd # df is your pandas DataFrame # Basic plot ax = df.plot(kind='line') plt.show()
Example
This example shows how to create a simple line plot from a pandas DataFrame with two columns representing data over days.
python
import matplotlib.pyplot as plt import pandas as pd # Create sample data data = {'Day': [1, 2, 3, 4, 5], 'Sales': [100, 150, 120, 170, 200], 'Expenses': [80, 90, 100, 110, 130]} df = pd.DataFrame(data) df.set_index('Day', inplace=True) # Plot the DataFrame ax = df.plot(kind='line', title='Sales and Expenses Over Days') ax.set_xlabel('Day') ax.set_ylabel('Amount') plt.show()
Output
A line plot window showing two lines: Sales and Expenses over days 1 to 5 with labeled axes and title.
Common Pitfalls
Common mistakes when plotting pandas DataFrames with matplotlib include:
- Not calling
plt.show(), so the plot does not display. - Forgetting to set an index if you want a meaningful x-axis.
- Using unsupported plot kinds or misspelling the
kindparameter. - Trying to plot non-numeric columns without preprocessing.
Always check your DataFrame structure before plotting.
python
import matplotlib.pyplot as plt import pandas as pd # Wrong: No plt.show(), plot won't display # df.plot() # Right: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) df.plot() plt.show()
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| kind | Type of plot to draw | 'line', 'bar', 'hist', 'box', 'scatter' |
| title | Title of the plot | 'Sales Over Time' |
| xlabel | Label for x-axis | 'Day' |
| ylabel | Label for y-axis | 'Amount' |
| legend | Show legend or not | True or False |
Key Takeaways
Use df.plot() to create plots from pandas DataFrames easily with matplotlib.
Always call plt.show() to display the plot window.
Set the DataFrame index for meaningful x-axis labels.
Choose the plot type with the kind parameter for different visualizations.
Check your data types to avoid errors when plotting.