Visualizing COVID-19 Cases for December Using Python
Data visualization is one of the most important parts of data analysis. Raw data stored inside spreadsheets or CSV files can be difficult to understand without proper visualization. Using Python libraries such as Pandas and Matplotlib, we can process large datasets and create meaningful visual representations.
In this tutorial, we will learn how to:
- Read COVID-19 data from a CSV file
- Preprocess the dataset
- Convert date values into datetime format
- Extract months from dates
- Filter records for December
- Create a line plot of COVID-19 cases
- Save the visualization as an image
By the end of this tutorial, you will understand how time-series datasets are handled in Python and how to generate meaningful visualizations using Pandas and Matplotlib.
Table of Contents
1. Importing Required Libraries
Before working with datasets and plots, we need to import the necessary Python libraries.
import pandas as pd
import matplotlib.pyplot as plt
Explanation
- Pandas is used for data analysis and manipulation.
- Matplotlib is used for creating charts and visualizations.
>>> import pandas as pd >>> import matplotlib.pyplot as plt >>>
Why Pandas Is Important in Data Science
Pandas provides powerful tools for:
- Reading CSV files
- Cleaning datasets
- Handling missing values
- Filtering rows and columns
- Performing statistical analysis
- Working with dates and time-series data
2. Reading the CSV File
The dataset is stored in a CSV file named ca-covid.csv.
df = pd.read_csv("ca-covid.csv")
This command loads the CSV file into a Pandas DataFrame.
What Is a DataFrame?
A DataFrame is a two-dimensional table-like data structure in Pandas. It contains:
- Rows
- Columns
- Indexes
Example Data
| date | state | cases |
|---|---|---|
| 01.12.20 | CA | 25000 |
| 02.12.20 | CA | 27000 |
CSV stands for Comma-Separated Values and is one of the most commonly used file formats in data science.
3. Data Preprocessing
Data preprocessing is a critical step in data analysis. Raw datasets often contain unnecessary columns or inconsistent formats.
Dropping the State Column
df.drop('state', axis=1, inplace=True)
Explanation
drop()removes a column or row.'state'is the column name.axis=1means column removal.inplace=Trueupdates the original DataFrame directly.
Understanding Dataset Dimensions
Suppose the dataset initially contains:
- \(n\) rows
- \(m\) columns
After removing one column:
$$ New\ Columns = m - 1 $$If:
$$ m = 3 $$Then:
$$ New\ Columns = 3 - 1 = 2 $$4. Converting Dates to DateTime Format
Dates stored as plain text are difficult to analyze. Converting them into datetime format enables advanced time-based operations.
df['date'] = pd.to_datetime(df['date'], format="%d.%m.%y")
Why DateTime Matters
- Sorting dates chronologically
- Extracting months and years
- Calculating trends
- Filtering time ranges
- Generating time-series plots
Date Format Explanation
| Format Code | Meaning |
|---|---|
| %d | Day |
| %m | Month |
| %y | Two-digit year |
Before Conversion: 01.12.20 After Conversion: 2020-12-01 00:00:00
5. Extracting the Month
df['month'] = df['date'].dt.month
This creates a new column called month.
Example
| Date | Extracted Month |
|---|---|
| 2020-12-01 | 12 |
| 2020-11-15 | 11 |
Time-Series Mathematics
Time-series analysis studies how data changes over time.
If:
- \(C_t\) = cases on day \(t\)
Then daily growth rate becomes:
$$ Growth\ Rate = \frac{C_t - C_{t-1}}{C_{t-1}} $$This formula helps analysts measure how rapidly infections increase or decrease.
6. Setting Date as Index
df.set_index('date', inplace=True)
The date column becomes the DataFrame index.
This improves time-series operations and plotting.
date 2020-12-01 2020-12-02 2020-12-03
7. Filtering Data for December
df[df['month']==12]['cases']
Explanation
df['month']==12filters December rows.['cases']selects only the cases column.
This produces a dataset containing only December COVID-19 case numbers.
8. Creating the Line Plot
df[df['month']==12]['cases'].plot()
This creates a line graph showing daily COVID-19 cases for December.
Why Use a Line Plot?
Line plots are excellent for time-series data because they:
- Show trends clearly
- Display increases and decreases
- Highlight spikes in cases
- Reveal patterns over time
Understanding Graph Slopes
The slope of the graph indicates the rate of change.
Slope formula:
$$ m = \frac{y_2 - y_1}{x_2 - x_1} $$Where:
- \(y\) represents cases
- \(x\) represents days
A positive slope means increasing cases. A negative slope means decreasing cases.
9. Saving the Plot
plt.savefig('plot.png')
This saves the visualization as an image file.
Benefits of Saving Plots
- Easy sharing
- Documentation
- Report generation
- Presentation usage
- Research publication
10. Displaying the Plot
plt.show()
This displays the graph on the screen.
Without
plt.show(), some environments may not display the graph visually.
Complete Python Program
import pandas as pd
import matplotlib.pyplot as plt
# Read CSV file
df = pd.read_csv("ca-covid.csv")
# Remove unnecessary column
df.drop('state', axis=1, inplace=True)
# Convert date column to datetime
df['date'] = pd.to_datetime(df['date'], format="%d.%m.%y")
# Extract month
df['month'] = df['date'].dt.month
# Set date as index
df.set_index('date', inplace=True)
# Plot December cases
df[df['month']==12]['cases'].plot()
# Save plot
plt.savefig('plot.png')
# Display plot
plt.show()
Expected Output
The output will include:
- A line graph showing daily COVID-19 cases for December
- A saved image file named
plot.png - A visual display of the graph on screen
Conclusion
This tutorial demonstrated how Python can be used to preprocess and visualize COVID-19 data efficiently. Using Pandas and Matplotlib together provides a powerful framework for handling time-series datasets and generating insightful visualizations.
The workflow included:
- Reading CSV data
- Cleaning unnecessary columns
- Converting dates
- Extracting month values
- Filtering December records
- Creating a line chart
- Saving the plot as an image
These same techniques can be applied to:
- Stock market analysis
- Weather forecasting
- Traffic analysis
- Business analytics
- Scientific research
- Healthcare reporting
Data visualization transforms raw information into understandable insights. Learning Pandas and Matplotlib is a foundational step toward mastering data science and analytics.
No comments:
Post a Comment