6.9 C
London
Thursday, December 19, 2024
HomePandas in PythonGeneral Functions in PythonHow to Plot Multiple Series from a Pandas DataFrame

How to Plot Multiple Series from a Pandas DataFrame

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to plot multiple series from a single pandas DataFrame:

plt.plot(df['series1'])
plt.plot(df['series2'])
plt.plot(df['series3'])

The following step-by-step example shows how to use this syntax in practice.

Step 1: Create the Data

First, let’s create a pandas DataFrame that contains the total sales made by three companies during an 8-week period:

import pandas as pd

#create data
df = pd.DataFrame({'A': [9, 12, 15, 14, 19, 23, 25, 29],
                   'B': [5, 7, 7, 9, 12, 9, 9, 14],
                   'C': [5, 4, 7, 13, 15, 15, 18, 31]})
#view data
print(df)

    A   B   C
0   9   5   5
1  12   7   4
2  15   7   7
3  14   9  13
4  19  12  15
5  23   9  15
6  25   9  18
7  29  14  31

Step 2: Plot Multiple Series

Next, let’s plot the sales of each company on the same chart:

import matplotlib.pyplot as plt

#plot each series
plt.plot(df['A'])
plt.plot(df['B'])
plt.plot(df['C'])

#display plot
plt.show()

Step 3: Add a Legend and Labels

Next, let’s add a legend and some axes labels to make the plot easier to read:

#plot individual lines with custom colors and labels
plt.plot(df['A'], label='A', color='green')
plt.plot(df['B'], label='B', color='steelblue')
plt.plot(df['C'], label='C', color='purple')

#add legend
plt.legend(title='Group')

#add axes labels and a title
plt.ylabel('Sales', fontsize=14)
plt.xlabel('Time', fontsize=14)
plt.title('Sales by Group', fontsize=16)

#display plot
plt.show()


You can find more pandas tutorials on this page.

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories