Skip to content

Commit a25d227

Browse files
Merge branch 'Codecademy:main' into main
2 parents e4aa0b1 + 645c9a9 commit a25d227

File tree

13 files changed

+1015
-0
lines changed

13 files changed

+1015
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
---
2+
Title: '.stackplot()'
3+
Description: 'Creates a stacked area plot to show how multiple datasets contribute cumulatively over time or categories.'
4+
Subjects:
5+
- 'Data Science'
6+
- 'Data Visualization'
7+
Tags:
8+
- 'Charts'
9+
- 'Matplotlib'
10+
- 'Stacks'
11+
CatalogContent:
12+
- 'learn-python-3'
13+
- 'paths/data-science'
14+
---
15+
16+
The **`.stackplot()`** method in Matplotlib creates stacked area plots (also known as stacked area charts) that display multiple datasets as vertically stacked areas. Each area represents the cumulative contribution of different categories to a total, making it ideal for visualizing proportional relationships as those relationships change over time.
17+
18+
## Syntax
19+
20+
```pseudo
21+
matplotlib.pyplot.stackplot(x, *args, labels=(), colors=None, hatch=None, baseline='zero', data=None, **kwargs)
22+
```
23+
24+
**Parameters:**
25+
26+
- `x`: Array-like. The x-coordinates of the data points.
27+
- `*args`: One or more array-like sequences representing the y-values for each stack layer.
28+
- `labels`: List of strings, optional. Labels for each stack layer (used in legends).
29+
- `colors`: List of colors or color specifications for each stack layer.
30+
- `hatch`: String or sequence, optional. Hatching patterns applied to the filled areas.
31+
- `baseline`: String, defines the baseline for stacking:
32+
- `'zero'` (default): Stack from y = 0.
33+
- `'sym'`: Symmetric stacking around zero.
34+
- `'wiggle'`: Minimizes slope changes between layers.
35+
- `'weighted_wiggle'`: Weighted version of the wiggle baseline.
36+
- `data`: Object with labeled data (e.g., dict or DataFrame). Optional data source.
37+
- `**kwargs`: Additional keyword arguments passed to `PolyCollection` (e.g., `alpha` for transparency).
38+
39+
**Return value:**
40+
41+
Returns a list of `PolyCollection` objects, one for each stack layer.
42+
43+
## Example 1: Visualizing Monthly Sales by Category
44+
45+
This example shows a stacked area chart of sales data across product categories over time:
46+
47+
```py
48+
import matplotlib.pyplot as plt
49+
50+
# Sample data
51+
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
52+
electronics = [20, 25, 30, 28, 35, 40]
53+
clothing = [15, 18, 22, 25, 20, 30]
54+
books = [10, 12, 15, 18, 22, 25]
55+
56+
# Create stacked area plot
57+
plt.stackplot(months, electronics, clothing, books,
58+
labels=['Electronics', 'Clothing', 'Books'],
59+
colors=['#ff9999', '#66b3ff', '#99ff99'],
60+
alpha=0.8)
61+
62+
plt.xlabel('Month')
63+
plt.ylabel('Sales (in thousands)')
64+
plt.title('Monthly Sales by Category')
65+
plt.legend(loc='upper left')
66+
plt.show()
67+
```
68+
69+
This creates a stacked area chart where each colored area represents a product category's contribution to total sales:
70+
71+
![Stackplot Example](https://raw.githubusercontent.com/Codecademy/docs/main/media/stackplot-example.png)
72+
73+
## Example 2: Stacked Areas with Multiple Series
74+
75+
This example demonstrates stacking multiple data series using numeric values:
76+
77+
```py
78+
import matplotlib.pyplot as plt
79+
import numpy as np
80+
81+
# Create sample data
82+
x = [1, 2, 3, 4, 5]
83+
y1 = [1, 2, 3, 2, 1]
84+
y2 = [2, 3, 2, 4, 3]
85+
y3 = [1, 1, 2, 1, 2]
86+
87+
# Create stackplot
88+
plt.stackplot(x, y1, y2, y3,
89+
labels=['Series A', 'Series B', 'Series C'],
90+
colors=['lightcoral', 'lightblue', 'lightgreen'],
91+
alpha=0.8)
92+
93+
plt.xlabel('X Values')
94+
plt.ylabel('Y Values')
95+
plt.title('Basic Stackplot Example')
96+
plt.legend(loc='upper left')
97+
plt.grid(True, alpha=0.3)
98+
plt.show()
99+
```
100+
101+
This creates a basic stacked area plot with three data series, demonstrating the fundamental structure of stackplot visualizations:
102+
103+
![Stackplot Example 2](https://raw.githubusercontent.com/Codecademy/docs/main/media/stackplot-example-2.png)
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
---
2+
Title: '.cumprod()'
3+
Description: 'Returns the cumulative product of array elements along a specified axis.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Linear Algebra'
10+
- 'Matrices'
11+
- 'NumPy'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/data-science'
15+
---
16+
17+
In NumPy, the **`.cumprod()`** method returns the cumulative product of the array elements over a particular axis. This method belongs to the `ndarray` class.
18+
19+
## Syntax
20+
21+
```pseudo
22+
ndarray.cumprod(axis=None, dtype=None, out=None)
23+
```
24+
25+
**Parameters:**
26+
27+
- `axis` (optional): Axis along which the cumulative product is computed. The default (None) flattens the array.
28+
- `dtype` (optional): The data type of the output array. Useful when input elements are of smaller types and may overflow.
29+
- `out` (optional): An alternative output array where results will be stored. It must have the same shape as the expected output.
30+
31+
**Return value:**
32+
33+
Returns a new array that contains the cumulative product of elements along the specified axis. If `out` is provided, the result is placed into it.
34+
35+
## Example 1: Cumulative Product of a 1D Array
36+
37+
This example computes the cumulative product of all elements in a one-dimensional array:
38+
39+
```py
40+
import numpy as np
41+
42+
a = np.array([1, 2, 3, 4])
43+
print("Original array:", a)
44+
45+
result = a.cumprod()
46+
print("Cumulative product:", result)
47+
```
48+
49+
The output of this code is:
50+
51+
```shell
52+
Original array: [1 2 3 4]
53+
Cumulative product: [ 1 2 6 24]
54+
```
55+
56+
Each element in the output represents the product of all elements up to that index in the input array.
57+
58+
## Example 2: Cumulative Product Along Different Axes
59+
60+
This example shows how `.cumprod()` behaves when applied across rows and columns of a 2D array:
61+
62+
```py
63+
import numpy as np
64+
65+
b = np.array([[1, 2, 3],
66+
[4, 5, 6]])
67+
68+
print("Original array:")
69+
print(b)
70+
71+
# Cumulative product along rows (axis=1)
72+
row_cumprod = b.cumprod(axis=1)
73+
print("\nCumulative product along rows (axis=1):")
74+
print(row_cumprod)
75+
76+
# Cumulative product along columns (axis=0)
77+
col_cumprod = b.cumprod(axis=0)
78+
print("\nCumulative product along columns (axis=0):")
79+
print(col_cumprod)
80+
```
81+
82+
The output of this code is:
83+
84+
```shell
85+
Original array:
86+
[[1 2 3]
87+
[4 5 6]]
88+
89+
Cumulative product along rows (axis=1):
90+
[[ 1 2 6]
91+
[ 4 20 120]]
92+
93+
Cumulative product along columns (axis=0):
94+
[[ 1 2 3]
95+
[ 4 10 18]]
96+
```
97+
98+
- When `axis=1`, the cumulative product is computed across each row.
99+
- When `axis=0`, it’s computed down each column.
100+
101+
## Codebyte Example
102+
103+
Run this interactive example to experiment with `.cumprod()` on a 2D array:
104+
105+
```codebyte/python
106+
import numpy as np
107+
108+
a = np.array([[2, 3, 4],
109+
[5, 6, 7]])
110+
111+
print("Original array:")
112+
print(a)
113+
114+
print("\nCumulative product (flattened):", a.cumprod())
115+
print("\nCumulative product along axis=0:\n", a.cumprod(axis=0))
116+
print("\nCumulative product along axis=1:\n", a.cumprod(axis=1))
117+
```
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
---
2+
Title: '.diagonal()'
3+
Description: 'Returns the specified diagonal elements of an array.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Linear Algebra'
10+
- 'Matrices'
11+
- 'NumPy'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/data-science'
15+
---
16+
17+
The **`.diagonal()`** method returns the specified diagonal elements of a NumPy array. For 2D arrays, the diagonal consists of elements where the row index equals the column index (or with an offset). For multi-dimensional arrays, the axes specified by `axis1` and `axis2` define the matrix dimensions from which to extract the diagonal.
18+
19+
Unlike [`.trace()`](https://www.codecademy.com/resources/docs/numpy/ndarray/trace), which returns the sum of diagonal elements, `.diagonal()` returns the actual diagonal elements as an array. This method typically returns a view rather than a copy, making it memory-efficient for large arrays.
20+
21+
## Syntax
22+
23+
```pseudo
24+
ndarray.diagonal(offset=0, axis1=0, axis2=1)
25+
```
26+
27+
**Parameters:**
28+
29+
- `offset` (Optional): The diagonal offset from the main diagonal. A positive value selects a diagonal above the main diagonal, while a negative value selects one below. Default is `0` (main diagonal).
30+
- `axis1` (Optional): The axis to be used as the first axis of the 2D sub-arrays from which the diagonals should be taken. Default is `0`.
31+
- `axis2` (Optional): The axis to be used as the second axis of the 2D sub-arrays from which the diagonals should be taken. Default is `1`.
32+
33+
**Return value:**
34+
35+
Returns an array containing the diagonal elements. For 2D arrays, this is a 1D array. For higher-dimensional arrays, the result has one fewer dimension than the input.
36+
37+
## Example 1: Extracting Diagonals from 2D and Rectangular Arrays
38+
39+
This example demonstrates how to extract diagonals from both square and rectangular arrays using different `offset` values:
40+
41+
```py
42+
import numpy as np
43+
44+
# Create a 3×3 square array
45+
square = np.array([[1, 2, 3],
46+
[4, 5, 6],
47+
[7, 8, 9]])
48+
49+
print("Square array:")
50+
print(square)
51+
52+
print("\nMain diagonal:", square.diagonal())
53+
print("Upper diagonal (offset=1):", square.diagonal(offset=1))
54+
print("Lower diagonal (offset=-1):", square.diagonal(offset=-1))
55+
56+
# Create a 4×3 rectangular array
57+
rectangular = np.array([[1, 2, 3],
58+
[4, 5, 6],
59+
[7, 8, 9],
60+
[10, 11, 12]])
61+
62+
print("\nRectangular array:")
63+
print(rectangular)
64+
65+
print("\nMain diagonal:", rectangular.diagonal())
66+
print("Upper diagonal (offset=1):", rectangular.diagonal(offset=1))
67+
print("Lower diagonal (offset=-2):", rectangular.diagonal(offset=-2))
68+
```
69+
70+
The output produced by this code is:
71+
72+
```shell
73+
Square array:
74+
[[1 2 3]
75+
[4 5 6]
76+
[7 8 9]]
77+
78+
Main diagonal: [1 5 9]
79+
Upper diagonal (offset=1): [2 6]
80+
Lower diagonal (offset=-1): [4 8]
81+
82+
Rectangular array:
83+
[[ 1 2 3]
84+
[ 4 5 6]
85+
[ 7 8 9]
86+
[10 11 12]]
87+
88+
Main diagonal: [1 5 9]
89+
Upper diagonal (offset=1): [2 6]
90+
Lower diagonal (offset=-2): [7 11]
91+
```
92+
93+
For rectangular matrices, the diagonal length is determined by the smaller dimension, and different offsets extract parallel diagonals above or below the main one.
94+
95+
## Example 2: Using `.diagonal()` with Multi-Dimensional Arrays
96+
97+
This example demonstrates how to extract diagonals from higher-dimensional arrays by specifying axes:
98+
99+
```py
100+
import numpy as np
101+
102+
# Create a 3D array (2x3x3)
103+
array_3d = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
104+
[[10, 11, 12], [13, 14, 15], [16, 17, 18]]])
105+
print("3D array shape:", array_3d.shape)
106+
print("3D array:")
107+
print(array_3d)
108+
109+
# Extract diagonal from the last two dimensions
110+
diag_default = array_3d.diagonal()
111+
print("\nDiagonal (axis1=0, axis2=1):")
112+
print(diag_default)
113+
114+
# Extract diagonal with different axes
115+
diag_12 = array_3d.diagonal(axis1=1, axis2=2)
116+
print("\nDiagonal (axis1=1, axis2=2):")
117+
print(diag_12)
118+
```
119+
120+
The output produced by this code is:
121+
122+
```shell
123+
3D array shape: (2, 3, 3)
124+
3D array:
125+
[[[ 1 2 3]
126+
[ 4 5 6]
127+
[ 7 8 9]]
128+
129+
[[10 11 12]
130+
[13 14 15]
131+
[16 17 18]]]
132+
133+
Diagonal (axis1=0, axis2=1):
134+
[[ 1 13]
135+
[ 2 14]
136+
[ 3 15]]
137+
138+
Diagonal (axis1=1, axis2=2):
139+
[[ 1 5 9]
140+
[10 14 18]]
141+
```
142+
143+
For 3D arrays, `.diagonal()` extracts diagonal elements from 2D slices defined by the specified axes, resulting in an array with one fewer dimension.
144+
145+
## Codebyte Example
146+
147+
Run the following codebyte example to understand the usage of the `.diagonal()` method:
148+
149+
```codebyte/python
150+
import numpy as np
151+
152+
# Create a 4x4 matrix
153+
matrix = np.array([[1, 2, 3, 4],
154+
[5, 6, 7, 8],
155+
[9, 10, 11, 12],
156+
[13, 14, 15, 16]])
157+
print("Original matrix:")
158+
print(matrix)
159+
160+
# Extract and display different diagonals
161+
print("\nMain diagonal:", matrix.diagonal())
162+
print("First upper diagonal:", matrix.diagonal(1))
163+
print("Second upper diagonal:", matrix.diagonal(2))
164+
print("First lower diagonal:", matrix.diagonal(-1))
165+
```

0 commit comments

Comments
 (0)