Mathew K Analytics

Lesson 48 · Mastering Pandas

How to Create Line, Bar, Histogram, and Box Plots Using Python and Pandas

In this lesson, you are going to explore simple but powerful ways to visualize data using pandas. We will use the Tips dataset, which contains restaurant…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb

Visualizing Data with Pandas: Line, Bar, Histogram, and Box Plots#

In this lesson, you are going to explore simple but powerful ways to visualize data using pandas.

We will use the Tips dataset, which contains restaurant bills and corresponding tips.

By the end, you will know how to quickly create line plots, bar plots, histograms, and box plots for your own data analysis.

import warnings
warnings.filterwarnings('ignore')

# Data setup (Restaurant Tips Dataset)
import seaborn as sns
import numpy as np
np.random.seed(42)
df = sns.load_dataset('tips')
print(df.shape)
print(df.head(3))
(244, 7)
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3

Quick Data Overview#

Let us examine what is in the dataset.

Notice the following columns:

  • total_bill: The total restaurant bill (including tip).
  • tip: The tip amount given by the customer.
  • sex: The gender of the bill payer.
  • smoker: Whether the party included smokers.
  • day: Day of the week.
  • time: Lunch or Dinner.
  • size: Number of people at the table.
# Checking for missing values
print(df.isnull().sum())
total_bill    0
tip           0
sex           0
smoker        0
day           0
time          0
size          0
dtype: int64
# Summary statistics
print(df.describe())
       total_bill         tip        size
count  244.000000  244.000000  244.000000
mean    19.785943    2.998279    2.569672
std      8.902412    1.383638    0.951100
min      3.070000    1.000000    1.000000
25%     13.347500    2.000000    2.000000
50%     17.795000    2.900000    2.000000
75%     24.127500    3.562500    3.000000
max     50.810000   10.000000    6.000000

Your First Plot: Line Plot of Total Bill#

Line plots are great for displaying continuous data and trends over an index.

Let us try plotting restaurant bills in the order they were recorded.

df['total_bill'].plot(kind='line', title='Total Bill Amounts (by entry)')
<Axes: title={'center': 'Total Bill Amounts (by entry)'}>
No description has been provided for this image
# Line plot of tips
df['tip'].plot(kind='line', title='Tip Amounts (by entry)')
<Axes: title={'center': 'Tip Amounts (by entry)'}>
No description has been provided for this image

Bar Plots: Comparing Tip Amounts by Day#

Bar plots are ideal for comparing quantities across categories.

For example, let us compare the average tip amount by day of the week.

# Compute mean tip per day and plot as bar chart
df.groupby('day')['tip'].mean().plot(kind='bar', title='Average Tip by Day', ylabel='Average Tip ($)')
<Axes: title={'center': 'Average Tip by Day'}, xlabel='day', ylabel='Average Tip ($)'>
No description has been provided for this image
# Bar plot: average total bill by smoker status
df.groupby('smoker')['total_bill'].mean().plot(kind='bar', title='Average Total Bill by Smoker', ylabel='Average Bill ($)')
<Axes: title={'center': 'Average Total Bill by Smoker'}, xlabel='smoker', ylabel='Average Bill ($)'>
No description has been provided for this image

Histograms: Distributions at a Glance#

Histograms provide a quick summary of the distribution of a numerical column.

Let us look at how total bills are distributed.

# Histogram of total_bill
df['total_bill'].plot(kind='hist', bins=20, title='Histogram of Total Bill', xlabel='Total Bill ($)')
<Axes: title={'center': 'Histogram of Total Bill'}, xlabel='Total Bill ($)', ylabel='Frequency'>
No description has been provided for this image
# Histogram of tips
df['tip'].plot(kind='hist', bins=15, title='Histogram of Tip Amounts', xlabel='Tip Amount ($)')
<Axes: title={'center': 'Histogram of Tip Amounts'}, xlabel='Tip Amount ($)', ylabel='Frequency'>
No description has been provided for this image

Box Plots: Summarizing Data and Outliers#

A box plot summarizes key percentiles and highlights outliers.

Let us draw a box plot to compare total bills by time of day (Dinner vs. Lunch).

df.boxplot(column='total_bill', by='time', grid=False)
<Axes: title={'center': 'total_bill'}, xlabel='time'>
No description has been provided for this image
# Box plot: tip amount by party size
df.boxplot(column='tip', by='size', grid=False)
<Axes: title={'center': 'tip'}, xlabel='size'>
No description has been provided for this image

Bringing It Together: Multiple Plots in One Figure#

You can show several charts together to compare trends or patterns.

Let us use pandas to create a two-by-two grid of line and bar plots.

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2, figsize=(10, 8))
df['total_bill'].plot(kind='line', ax=axs[0,0], title='Total Bill (Line)')
df['tip'].plot(kind='line', ax=axs[0,1], title='Tip (Line)', color='darkgreen')
df.groupby('day')['tip'].mean().plot(kind='bar', ax=axs[1,0], title='Average Tip by Day')
df['total_bill'].plot(kind='hist', bins=15, ax=axs[1,1], title='Total Bill Histogram', color='orange')
plt.tight_layout()
No description has been provided for this image

Challenge: Try Your Own Plots#

Create a histogram for the size column. Or, make a box plot showing tips by gender.

Remember: Use .plot(kind=...) with different kind values.

Pause and experiment for a few minutes.

# Extra: Save a plot as an image file
ax = df['total_bill'].plot(kind='hist', bins=15, title='Total Bill Histogram')
fig = ax.get_figure()
fig.savefig('total_bill_histogram.png')
No description has been provided for this image

Recap: What You Learned#

You created line, bar, histogram, and box plots using pandas.

You learned how to quickly explore patterns and outliers in real data.

Try using these plot types any time you work with your own datasets!

Happy coding!

Next Steps: Join the Community#

If you liked this lesson, subscribe for more practical data science.

Comment which other plots or datasets you want to see next!

Keep exploring and visualizing new ideas.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.