Preparation
Before any data manipulation can occur, three (3) new libraries will require installation.
- The Pandas library enables access to/from a DataFrame.
- The Matplotlib library displays a visual graph of a plotted dataset.
- The Scipy library allows users to manipulate and visualize the data.
To install these libraries, navigate to an IDE terminal. At the command prompt ($
), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($
). Your terminal prompt may be different.
$ pip install pandas
Hit the <Enter>
key on the keyboard to start the installation process.
$ pip install matplotlib
Hit the <Enter>
key on the keyboard to start the installation process.
$ pip install scipy
Hit the <Enter>
key on the keyboard to start the installation process.
If the installations were successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required libraries.
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import pandas as pd import matplotlib.pyplot as plt import scipy
DataFrame Plot Area
The DataFrame.plot.area()
method creates a stacked Area plot chart.
The syntax for this method is as follows:
DataFrame.plot.area(x=None, y=None, **kwargs)
x | This parameter determines the coordinates for the x-axis. The default value is the index. |
y | This parameter specifies the coordinates for the y axis. The default value is the columns. |
**kwargs | Additional keywords are outlined above in the plot method. |
For this example, Rivers Clothing would like to plot an Area chart indicating Sales, New Customers, and Unique Visits to their online store over six (6) months.
df = pd.DataFrame({'Sales': [3, 2, 3, 9, 10, 6], 'New-Custs': [7, 7, 6, 11, 17, 13], 'Visits': [19, 41, 26, 61, 71, 60]}, index=pd.date_range(start='2022/01/01', end='2022/07/01', freq='M')) ax = plt.gca() df.plot.area(title='Sales Stats - 6 Months', fontsize=8, ax=ax) plt.show()
- Line [1] creates a DataFrame from a dictionary of lists. This output saves to
df
. - Line [2] creates an index based on a date range and frequency.
- Line [3] Gets the current access (
gca()
) and saves it toax
. - Line [4] does the following:
- creates the Area chart
- sets the title and font size
- sets the
ax
variable created above
- Line [5] outputs the Area chart on-screen.
Output
The buttons on the bottom left can be used to further manipulate the chart.
π‘ Note: Another way to create this chart is with the plot()
method and the kind
parameter set to the 'area'
option.
More Pandas DataFrame Methods
Feel free to learn more about the previous and next pandas DataFrame methods (alphabetically) here:
Also, check out the full cheat sheet overview of all Pandas DataFrame methods.