How to plot pie chart in python using csv file

Last update on August 19 2022 21:50:29 (UTC/GMT +8 hours)

Matplotlib Pie Chart: Exercise-4 with Solution

Write a Python programming to create a pie chart of gold medal achievements of five most successful countries in 2016 Summer Olympics. Read the data from a csv file.

Sample data:
medal.csv
country,gold_medal
United States,46
Great Britain,27
China,26
Russia,19
Germany,17

Sample Solution:

Python Code:

import matplotlib.pyplot as plt
import pandas as pd
df =  pd.read_csv('medal.csv')
country_data = df["country"]
medal_data = df["gold_medal"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
explode = (0.1, 0, 0, 0, 0)  
plt.pie(medal_data, labels=country_data, explode=explode, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.title("Gold medal achievements of five most successful\n"+"countries in 2016 Summer Olympics")
plt.show()

Sample Output:

How to plot pie chart in python using csv file

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python programming to create a pie chart with a title of the popularity of programming Languages. Make multiple wedges of the pie.
Next: Matplotlib Scatter Plot Exercises

I have this CSV data file, I'm trying to make a pie chart using this data

I'm a beginner in python and don't understand how to create a pie chart using the three columns, please help!

working solution code would be more helpful!

My code:

import pandas as pd
import matplotlib.pyplot as plt 

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

product_data = df["Product Name;"]   
bug_data = df["Number Of Bugs"]                      
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]    

plt.pie(bug_data , labels=product_data , colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)

plt.show()

the pie chart which is outputed by this code is distorted, any help?

Chart I'm getting:

How to plot pie chart in python using csv file

Stay productive and learn to #codefromhome during the pandemic.

How to plot pie chart in python using csv file

Photo by Annie Spratt on Unsplash

Suddenly everything changes—as if the whole world has stopped since coronavirus. I am worried about my family and friends. I had to cancel some schedules. None of my plans could work at this time of pandemic. However, I refuse to get stuck and make it worse. I just believe that tomorrow will be better than today.

How are you keeping productive in COVID-19 self-isolation and social distancing? You can try by getting started with the very basic of data visualization. Here it is!

According to Wikipedia,

“Data visualization is the graphic representation of data. It involves producing images that communicate relationships among the represented data to viewers of the images.”

It is important to design the proper visualizations for your data. For this post, I would like to use the data of COVID-19 in South Korea provided originally by KCDC (Korea Centers for Disease Control & Prevention).

Creating Bar Chart

I choose a bar chart to visualize the total number of confirmed COVID-19 infection cases Case.csv found at each province in South Korea.

Let’s get started by importing pandas library for dataframe analysis.

import pandas as pd

For the next step, read the .csv file and save it to pandas dataframe df1 to ease the data manipulation.

df1 = pd.read_csv(‘Case.csv’)
df1.head()

How to plot pie chart in python using csv file

To get the total number of confirmed cases, I will sum up the number for each province and create a new dataframe data_bar. Here, I use the aggregation function agg and rename the column.

data = {‘confirmed’:’sum_confirmed’}
agg_data = {‘confirmed’:’sum’}
data_bar = df1.groupby([‘province’], as_index=False).agg(agg_data).rename(columns=data)

Here is the output of my new dataframe.

data_bar

How to plot pie chart in python using csv file

Import matplotlib and numpy libraries before getting started with the bar chart. I will generate an array based on the length of province as the label and save it as index to use it on X-axis. My Y-axis comes from the sum of confirmed cases. Then, I also add the xlabel and ylabel to make the data clearly presented.

import matplotlib.pyplot as plt
import numpy as np
index = np.arange(len(data_bar.province))
plt.bar(index, data_bar.sum_confirmed)
plt.xlabel(‘Province’, fontsize=8)
plt.ylabel(‘Accumulated Num Confirmed’, fontsize=8)
plt.xticks(index, data_bar.province, fontsize=7, rotation=75)
plt.title(‘Number of the confirmed COVID-19 Cases in South Korea’)
plt.show()

The bar chart should look like this.

How to plot pie chart in python using csv file

Output of the bar chart — with Daegu as one province with the highest number of confirmed COVID-19 cases

Creating Pie Chart

Next, I’ll continue to present the age demographic of COVID-19 patients across South Korea (I’m using PatientInfo.csv as the datasource). I choose a pie chartas the visualization.

First of all, read the .csv file and save it to pandas dataframe df2.

df2 = pd.read_csv(‘PatientInfo.csv’)
df2.head()

How to plot pie chart in python using csv file

I am cleaning the data to make sure there is no missing value in age column df2 = df2.dropna(subset=['age'].

To get the total number of patients for each age, I create a new dataframe data_pie and save the values.

data_pie = df2[‘age’].value_counts().rename_axis(‘age’).reset_index(name=’patients_count’)

Thematplotlib and numpy library are needed if they haven’t been imported yet. I’m using age as labels and patients_count as sizes, also presented the number as percentage autopct='%.1f%%'. Modify the startangle to get the preferred direction (here I’m using 90 degree as my starting point). To change the size of the chart, simply modify the figsize.

The complete code for the chart are presented below.

plt.figure(figsize=(10,10))
plt.pie(data_pie.patients_count, labels=data_pie.age, startangle=90, autopct=’%.1f%%’)
plt.title(‘The Age of Patients’)
plt.show()

Voila! Here is the pie chart.

How to plot pie chart in python using csv file

Output of the pie chart — COVID-19 patients are dominated by age of 20s, 40s and 50s

How do you plot a graph from CSV in Python?

MatPlotLib with Python.
Set the figure size and adjust the padding between and around the subplots..
Make a list of headers of the . CSV file..
Read the CSV file with headers..
Set the index and plot the dataframe..
To display the figure, use show() method..

How do I Visualise data from a CSV file in Python?

The approach of the program:.
Import required libraries, matplotlib library for visualizing, and CSV library for reading CSV data..
Open the file using open( ) function with 'r' mode (read-only) from CSV library and read the file using csv. ... .
Read each line in the file using for loop..
Append required columns into a list..

How do I convert a CSV file to a graph?

How to Graph a CSV File in Excel.
Open your CSV file in MS Excel. Video of the Day..
Select the data cells you would like to graph by clicking on the corner cell and dragging the cursor to the far corner. Release the mouse button..