Data Visualization with Pandas is the presentation of data in a graphical format. It helps people understand the significance of data by summarizing and presenting a huge amount of data in a simple and easy-to-understand format and helps communicate information clearly and effectively. In this tutorial, we will explore how to leverage Pandas for creating various types of plots, making your data analysis more intuitive and insightful.

Data Visualization with Pandas
Pandas is a powerful open-source data analysis and manipulation library for Python. It provides data structures and functions needed to work with structured data seamlessly. The library is particularly well-suited for handling labeled data, such as tables with rows and columns, making it a staple in the data science community.
Key Features for Data Visualization with Pandas:
Pandas offers several features that make it a great choice for data visualization:
- Variety of Plot Types: Pandas supports various plot types, including line plots, bar plots, histograms, box plots, and scatter plots, catering to different visualization needs.
- Customization: Users can customize plots by adding titles, labels, and styling, enhancing the readability and aesthetics of the visualizations.
- Handling of Missing Data: Pandas efficiently handles missing data, ensuring that visualizations accurately represent the dataset without errors.
- Integration with Matplotlib: Pandas seamlessly integrates with Matplotlib, allowing users to create a wide range of static, animated, and interactive plots.
Before diving into data visualization, ensure you have Pandas installed. You can install it using pip:
pip install pandas

Installing Pandas for Data Visualization
For more, refer to below links:
To perform basic plotting with Pandas, we can leverage the built-in plot() method, which is a wrapper around Matplotlib’s plotting functions. You can also just call df.plot(kind=’hist’) or replace that kind argument with any of the key terms shown in the list above (e.g. ‘box’, ‘barh’, etc.). Let’s start going through them with examples:
Loading Data into Pandas
For this tutorial, let’s create a simple DataFrame to work with( Note: Data frame for line plot will be different)
Python
import pandas as pd
# Defining the data as a dictionary, including the missing rows with made-up values
data = {
'Column1': [0.039762, 0.937288, 0.780504, 0.672717, 0.053829,
0.845678, 0.123456, 0.987654, 0.543210, 0.876543,
0.234567, 0.654321, 0.345678, 0.789012, 0.456789,
0.723456, 0.234567, 0.876543, 0.123456, 0.543210],
'Column2': [0.218517, 0.041567, 0.008948, 0.247870, 0.520124,
0.354321, 0.678912, 0.012345, 0.789012, 0.345678,
0.901234, 0.234567, 0.345678, 0.456789, 0.567890,
0.189234, 0.456789, 0.012345, 0.901234, 0.345678],
'Column3': [0.103423, 0.899125, 0.557808, 0.264071, 0.552264,
0.789012, 0.456789, 0.123456, 0.234567, 0.345678,
0.567890, 0.678901, 0.789012, 0.890123, 0.901234,
0.612378, 0.345678, 0.765432, 0.234567, 0.876543],
'Column4': [0.957904, 0.977680, 0.797510, 0.444358, 0.190008,
0.876543, 0.234567, 0.345678, 0.456789, 0.567890,
0.678901, 0.789012, 0.890123, 0.901234, 0.123456,
0.876543, 0.901234, 0.543210, 0.876543, 0.123456]
df = pd.DataFrame(data)
A line plot is a graph that shows the frequency of data along a number line. It is best to use a line plot when the data is time series. It is a quick, simple way to organize data.
The Syntax is : df.plot.line
Python
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Year': [2015, 2016, 2017, 2018, 2019, 2020],
'Sales': [200, 250, 300, 350, 400, 450],
'Profit': [20, 30, 50, 70, 90, 110]
}
df = pd.DataFrame(data)
# Plotting both Sales and Profit over the years
ax = df.plot(x='Year', y='Sales', kind='line', marker='o', title='Sales and Profit Over Years')
df.plot(x='Year', y='Profit', kind='line', marker='s', ax=ax, secondary_y=True)
# Adding labels and grid
ax.set_ylabel('Sales')
ax.right_ax.set_ylabel('Profit')
ax.grid(True)
plt.show()
Output :

Line Plot with Pandas
A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a line graph.
Python
Output:

Bar Plot with Pandas
We can also create stacked bar chart. Stacked bar plots are an excellent way to visualize data that is divided into different categories.
- They allow you to see both the total size of categories and the contribution of each sub-category.
- The height of each bar reflects the cumulative total of the sub-categories.
Python
df.plot.bar(stacked=True)
Output :

Stacked bar plots
An area chart or area graph displays graphically quantitative data. It is based on the line chart. The area between axis and line are commonly emphasized with colors, textures and hatchings. Commonly one compares two or more quantities with an area chart.
Python
Output :

Area Plot
To create a density plot in Pandas, you can use the plot.kde() or plot.density() methods, which are essentially interchangeable and use Kernel Density Estimation (KDE) to estimate the probability density function (PDF) of a random variable.
KDE is a technique that let’s you create a smooth curve given a set of data.
- This can be useful if you want to visualize just the “shape” of some data, as a kind of continuous replacement for the discrete histogram.
- It can also be used to generate points that look like they came from a certain dataset – this behavior can power simple simulations, where simulated objects are modeled off of real data.
Python
Output :

Kernel Density Estimation (KDE) Plot
Example : Density Plot
Python
Output :

Density Plot
A histogram is a plot that lets you discover, and show, the underlying frequency distribution (shape) of a set of continuous data. This allows the inspection of the data for its underlying distribution (e.g., normal distribution), outliers, skewness, etc.
Python
df['A'].plot.hist(bins=50)
Output :

Histogram Plot
Scatter plots are used when you want to show the relationship between two variables. Scatter plots are sometimes called correlation plots because they show how two variables are correlated.
Python
df.plot.scatter(x='A', y='B')
Output :

Scatter Plot
For customization, we can use s to indicate size based off another column. s parameter needs to be an array, not just the name of a column:
Python
df.plot.scatter(x ='A', y ='B', s = df1['C']*200)
Output :

A boxplot is a standardized way of displaying the distribution of data based on a five-number summary (“minimum”, first quartile (Q1), median, third quartile (Q3), and “maximum”). It can tell you about your outliers and what their values are. It can also tell you if your data is symmetrical, how tightly your data is grouped, and if and how your data is skewed.
Python
df.plot.box() # Can also pass a by = argument for groupby
Output:

Box Plot
8. Hexagonal Bin Plots
Hexagonal Binning is another way to manage the problem of having too many points that start to overlap. Hexagonal binning plots density, rather than points.
- Points are binned into gridded hexagons and distribution (the number of points per hexagon) is displayed using either the color or the area of the hexagons.
- Useful for Bivariate Data, an alternative to scatterplot.
Python
df = pd.DataFrame(np.random.randn(1000, 2), columns =['a', 'b'])
df.plot.hexbin(x ='a', y ='b', gridsize = 25, cmap ='Oranges')
Output :

Hexbin Plot
Customizing Pandas Plots Using Python
To customize plots in Pandas using various techniques such as adding titles, labels, and applying style sheets, you can directly use Pandas’ plotting capabilities, which are built on top of Matplotlib. This allows you to leverage the power of Matplotlib’s styling and customization options while working within the Pandas framework.
Customizing Plots in Pandas:
- Adding Titles and Labels: This enhances the clarity and context of your visualizations.
- Using Style Sheets: Applying style sheets improves consistency and readability across multiple plots.
1. Adding Titles and Labels
- Adding Titles and Labels: In Pandas, you can easily add a title to your plot using the
title parameter in the plot method. - Axis Labels: In Pandas, you can set axis labels using the
set_xlabel and set_ylabel methods on the plot’s axis object. For adding labels, set_xlabel() and set_ylabel() are used to label the x-axis and y-axis, respectively. Custom font sizes can make the labels more readable.
Here is an example of how to add titles and labels to a Pandas plot:
Python
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Year': [2015, 2016, 2017, 2018, 2019, 2020],
'Sales': [200, 250, 300, 350, 400, 450],
'Profit': [20, 30, 50, 70, 90, 110]
}
df = pd.DataFrame(data)
ax = df.plot(x='Year', y='Sales', kind='line', title='Sales Over Years', legend=True, marker='o')
# Adding title and axis labels
ax.set_title('Sales and Profit Over Years', fontsize=14, fontweight='bold')
ax.set_xlabel('Year', fontsize=12)
ax.set_ylabel('Sales', fontsize=12)
plt.show()
Output:

Adding Titles and Labels
2. Adding a Secondary Y-Axis
Using ax.twinx() creates a secondary y-axis for the “Profit” data, allowing for dual data representation on the same plot. This helps in visualizing two related data series with different scales.
Python
import pandas as pd
import matplotlib.pyplot as plt
# Sample DataFrame
data = {
'Year': [2015, 2016, 2017, 2018, 2019, 2020],
'Sales': [200, 250, 300, 350, 400, 450],
'Profit': [20, 30, 50, 70, 90, 110]
}
df = pd.DataFrame(data)
ax = df.plot(x='Year', y='Sales', kind='line', title='Sales Over Years', legend=True, marker='o')
# Adding a secondary y-axis for Profit
ax2 = ax.twinx()
df.plot(x='Year', y='Profit', kind='line', ax=ax2, color='r',legend=False, marker='s')
ax2.set_ylabel('Profit', fontsize=12)
plt.show()
Output:

With Secondary Axis
3. Additional Customizations Using Pandas
To further customize plots using Pandas, you can take advantage of additional features such as adjusting line styles, setting colors, modifying plot sizes, adding gridlines, customizing tick marks, and more. Let’s expand on the example provided earlier by incorporating more customizations directly using Pandas’ plotting capabilities.
- Changing Line Styles and Colors: Adjust line styles and colors to make plots more visually distinct.
- Modifying Plot Size: Change the size of the plot to better fit the presentation or analysis context.
- Customizing Tick Marks: Customize tick marks for better precision and presentation.
- Adding Annotations: Include annotations to highlight specific points of interest.
- Changing Font Properties: Customize fonts for better readability or to match presentation styles.
Python
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Year': [2015, 2016, 2017, 2018, 2019, 2020],
'Sales': [200, 250, 300, 350, 400, 450],
'Profit': [20, 30, 50, 70, 90, 110]
}
df = pd.DataFrame(data)
plt.figure(figsize=(10, 6))
# Creating a plot with more customization
ax = df.plot(
x='Year',
y='Sales',
kind='line',
linestyle='--', # Dashed line style
color='blue', # Line color
marker='o', # Circle markers
markersize=8, # Size of the markers
title='Sales and Profit Over Years',
legend=True
)
# Adding gridlines
ax.grid(which='both', linestyle='--', linewidth=0.7)
# Customizing tick marks
ax.set_xticks(df['Year']) # Set custom ticks for x-axis
ax.tick_params(axis='x', rotation=45, labelsize=12)
ax.tick_params(axis='y', labelsize=12)
ax2.tick_params(axis='y', labelsize=12)
# Adding annotations
for i, txt in enumerate(df['Sales']):
ax.annotate(txt, (df['Year'][i], df['Sales'][i]), textcoords="offset points", xytext=(0,5), ha='center', fontsize=10, color='blue')
# for i, txt in enumerate(df['Profit']):
ax2.annotate(txt, (df['Year'][i], df['Profit'][i]), textcoords="offset points", xytext=(0,5), ha='center', fontsize=10, color='red')
plt.show()
Output:

Customizing Plot Using Pandas
By incorporating these customizations, you can create more sophisticated and informative plots using Pandas, which enhances both the readability and aesthetics of your visualizations.
Visualizing Grouped and Faceted Plots With Pandas
Grouped and faceted plots are powerful visualization techniques used to compare different subsets of data across multiple categories or groups.
- Grouped plots allow you to visualize data from multiple categories on the same axes, making it easier to see comparisons and trends.
- Faceted plots, on the other hand, involve creating a grid of plots where each plot represents a subset of the data, allowing for easy visual comparison across different groups or categories.
1. Grouped Bar Plots
A grouped bar plot allows you to compare the values of different categories for each group.
For example, if you have sales data for different regions and different product categories, you can use a grouped bar plot to visualize the sales figures for each product category across the regions.
Python
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Region': ['North', 'North', 'South', 'South', 'East', 'East', 'West', 'West'],
'Category': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],
'Sales': [100, 150, 200, 250, 300, 350, 400, 450]
}
df = pd.DataFrame(data)
# Create a pivot table
pivot_df = df.pivot(index='Region', columns='Category', values='Sales')
# Plot grouped bar plot
pivot_df.plot(kind='bar', stacked=False)
plt.title('Sales by Region and Category')
plt.xlabel('Region')
plt.ylabel('Sales')
plt.show()
Output:

Grouped bar plot
- In this example, the
pivot() function reshapes the DataFrame, and the plot(kind='bar', stacked=False) creates a grouped bar plot. - Each bar group represents a different region, and within each group, bars represent different categories.
2. Faceted Line Plots
- Faceted line plots allow you to create multiple line plots, each representing a subset of data based on a categorical variable.
- This technique is useful for visualizing trends or patterns over time across different groups.
Python
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Date': pd.date_range(start='2024-01-01', periods=10, freq='D'),
'Sales_A': [100, 120, 150, 130, 160, 180, 200, 220, 210, 230],
'Sales_B': [90, 110, 130, 125, 155, 175, 190, 210, 205, 225],
'Category': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B']
}
df = pd.DataFrame(data)
# Facet plot
categories = df['Category'].unique()
fig, axes = plt.subplots(nrows=1, ncols=len(categories), figsize=(10, 4), sharey=True)
for i, category in enumerate(categories):
subset = df[df['Category'] == category]
axes[i].plot(subset['Date'], subset['Sales_A'], label='Sales A')
axes[i].plot(subset['Date'], subset['Sales_B'], label='Sales B')
axes[i].set_title(f'Category {category}')
axes[i].set_xlabel('Date')
if i == 0:
axes[i].set_ylabel('Sales')
axes[i].legend()
plt.tight_layout()
plt.show()
Output:

Faceted Plot
In this example, the dataset contains sales data for two categories (‘A’ and ‘B’) over time. Using plt.subplots(), we create a subplot for each category, allowing us to compare the sales trends between the two categories over time. By leveraging Pandas integration with Matplotlib, we can easily create these plots to compare multiple categories or subgroups, analyze trends over time, and visualize distributions.
When dealing with large datasets, it’s often useful to visualize a smaller, representative sample or use aggregated data to avoid overplotting and to maintain performance.
Pandas, provides several strategies to handle large datasets effectively. These strategies include downsampling, aggregation, and using representative samples to reduce the computational load and improve the readability of visualizations.
This section will explore these techniques in detail, providing examples of how to implement them in Pandas.
1. Downsampling with Pandas
Downsampling involves taking a random sample of the dataset to visualize a subset, which can help in understanding the general trend without plotting every single data point.
Python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Simulate a large dataset with 1,000,000 points
np.random.seed(0)
data = {
'x': np.random.rand(1000000),
'y': np.random.rand(1000000)
}
df = pd.DataFrame(data)
# Downsample by taking a random sample of 1% of the data
df_sample = df.sample(frac=0.01)
ax = df_sample.plot.scatter(x='x', y='y', alpha=0.5, color='blue')
ax.set_title('Scatter Plot of Downsampled Data')
plt.show()
Output:

Handling Large Datasets with Pandas Visualization
In this example:
- We create a large dataset of random values with 1 million rows.
- We use
.sample(frac=0.01) to randomly select 1% of the data for visualization. - The scatter plot is created using Pandas’ built-in
plot.scatter method.
Aggregation involves summarizing data by grouping and calculating aggregate statistics such as mean, median, or sum. This is particularly useful when you want to visualize trends over time or in categorical data.
Python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
date_range = pd.date_range(start='2024-01-01', periods=1000000, freq='T') # 1 million minutes
data = {
'timestamp': date_range,
'value': np.random.rand(len(date_range))
}
df = pd.DataFrame(data)
# Aggregate data by day and calculate the mean value for each day
df['date'] = df['timestamp'].dt.date
df_agg = df.groupby('date')['value'].mean().reset_index()
ax = df_agg.plot(x='date', y='value', kind='line', figsize=(12, 6))
ax.set_title('Daily Average Values Over Time')
ax.set_xlabel('Date')
ax.set_ylabel('Average Value')
plt.show()
Output:

Handling Large Datasets with Pandas Visualization
In this example:
- We create a time-series dataset with 1 million rows representing data points recorded every minute.
- We aggregate the data by day, calculating the mean value for each day using
groupby and mean. - The resulting daily averages are plotted as a line plot to show trends over time.
Conclusion
Data visualization with Pandas is a powerful tool for presenting data in a clear and insightful manner. By leveraging Pandas’ integration with Matplotlib and its built-in plotting capabilities, you can create a wide variety of plots to explore and communicate your data effectively.
Data Visualization with Pandas – FAQs
How does Pandas handle missing data in visualizations?
Pandas efficiently handles missing data by either ignoring them in visualizations or providing options to fill or interpolate missing values. This ensures that the visualizations accurately represent the dataset without errors.
How do you visualize a pandas DataFrame?
To visualize a Pandas DataFrame, use the df.plot() method. This leverages Matplotlib to create various plot types like line, bar, histogram, and scatter plots. Customize plots with titles, labels, and styles for clarity.
Why is Pandas a popular choice for data visualization in Python?
Pandas is popular for data visualization in Python because it provides a simple interface for creating plots directly from DataFrames. It also integrates well with other libraries like Matplotlib and Seaborn, making it versatile for both basic and complex visualizations.
Can I create interactive plots with Pandas?
While Pandas itself is primarily used for static plots, it can be combined with libraries like Plotly or Bokeh to create interactive visualizations. These libraries offer additional features for interactivity and dynamic data exploration.