Saturday 7 October 2023

How to Visualize Data from a CSV File with Pandas and Pyplot?

In this post, I am going to explain how to visualize the data from a csv file with Pandas and Pyplot.

Step 1: Create inflation.csv file with below content.

 

inflation.csv

Year,India,China,Australia,America,Canada,Japan
2013,6.2,2.3,2.7,1.7,1.3,0.7
2014,5.4,2.1,2.5,1.8,1.4,0.8
2015,4.9,2,2.6,1.9,1.5,0.9
2016,5.2,1.8,2.4,1.9,1.6,0.9
2017,3.8,2.9,2.0,2.2,1.7,0.8
2018,4.5,2.9,2.2,2.4,1.8,1.0
2019,4.8,3.0,2.3,2.5,1.9,1.1
2020,6.2,3.7,2.5,2.6,2.0,1.2
2021,5.6,3.9,2.7,2.7,2.1,1.3
2022,6.3,4.6,2.8,2.8,2.2,1.4

Step 2: Read the csv file data to a dataframe.

df = pd.read_csv('inflation.csv')

Step 3: Plot line graph using China and India inflation data.

plt.plot(df['Year'], df['India'], color='red', label='india', markersize=5, marker='o')
plt.plot(df['Year'], df['China'], color='blue', label='india', markersize=5, marker='x')

Find the below working application.

 

hello_world.py

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('inflation.csv')

plt.plot(df['Year'], df['India'], color='red', label='india', markersize=5, marker='o')
plt.plot(df['Year'], df['China'], color='blue', label='india', markersize=5, marker='x')

plt.show()

Output




Let’s use a for loop to print all the countries inflation data in line graph.

for column in df:
    if column != 'Year':
        plt.plot(df['Year'], df[column], marker='.', label=column)

Find the below working application.

 

another_example.py

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('inflation.csv')

for column in df:
    if column != 'Year':
        plt.plot(df['Year'], df[column], marker='.', label=column)

plt.legend()
plt.show()

Output





 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment