0
0
MatplotlibHow-ToBeginner ยท 3 min read

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 kind parameter.
  • 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

ParameterDescriptionExample
kindType of plot to draw'line', 'bar', 'hist', 'box', 'scatter'
titleTitle of the plot'Sales Over Time'
xlabelLabel for x-axis'Day'
ylabelLabel for y-axis'Amount'
legendShow legend or notTrue 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.