Skip to content

Commit 5434094

Browse files
authored
Merge branch 'main' into feat/add-numpy-byteswap-term
2 parents 447781f + ca80eb6 commit 5434094

File tree

16 files changed

+1099
-0
lines changed

16 files changed

+1099
-0
lines changed
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
---
2+
Title: '.axis()'
3+
Description: 'Gets or sets the properties of the plot axes, including axis limits, scaling, and visibility.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
- 'Data Visualization'
8+
Tags:
9+
- 'Data'
10+
- 'Graphs'
11+
- 'Libraries'
12+
- 'Matplotlib'
13+
- 'Plotting'
14+
CatalogContent:
15+
- 'learn-python-3'
16+
- 'paths/computer-science'
17+
---
18+
19+
The **`.axis()`** function in Matplotlib's [`pyplot`](https://www.codecademy.com/resources/docs/matplotlib/pyplot) module gets or sets properties of the plot axes, including axis limits, aspect ratio, and visibility.
20+
21+
## Syntax
22+
23+
```pseudo
24+
matplotlib.pyplot.axis(arg=None, emit=True, **kwargs)
25+
```
26+
27+
The function can be called in several ways:
28+
29+
- `axis()`: Returns current axis limits as `(xmin, xmax, ymin, ymax)`
30+
- `axis([xmin, xmax, ymin, ymax])`: Sets axis limits
31+
- `axis(option)`: Sets axis properties using predefined options
32+
- `axis(**kwargs)`: Sets axis properties using keyword arguments
33+
34+
**Parameters:**
35+
36+
- `arg` (optional): Defines how the axes are set or displayed. Accepts the following values:
37+
- A list or tuple `[xmin, xmax, ymin, ymax]` to set axis limits.
38+
- `'off'` to hide the axes.
39+
- `'on'` to show the axes.
40+
- `'equal'`, `'scaled'`, `'tight'`, `'auto'`, `'image'`, `'square'` — control axis scaling and aspect ratio.
41+
- `emit` (bool, default: True): If `True`, notifies observers of axis limit changes.
42+
- `kwargs` (optional): Additional axis properties such as `xmin`, `xmax`, `ymin`, and `ymax`.
43+
44+
**Return value:**
45+
46+
Returns a [tuple](https://www.codecademy.com/resources/docs/python/tuples) `(xmin, xmax, ymin, ymax)` representing the current axis limits.
47+
48+
## Example 1: Using `.axis()` to Control Axis Properties
49+
50+
This example creates three subplots demonstrating different axis control modes. The first subplot uses `axis([2, 8, -0.5, 0.5])` to restrict the view to specific x and y ranges. The second subplot uses `axis('equal')` to ensure both axes use the same scale. The third subplot uses `axis('off')` to hide the axis lines, ticks, and labels:
51+
52+
```py
53+
import matplotlib.pyplot as plt
54+
import numpy as np
55+
56+
# Generate sample data
57+
x = np.linspace(0, 10, 100)
58+
y = np.sin(x)
59+
60+
# Create a basic plot
61+
plt.figure(figsize=(10, 4))
62+
63+
# Subplot 1: Custom axis limits
64+
plt.subplot(1, 3, 1)
65+
plt.plot(x, y)
66+
plt.axis([2, 8, -0.5, 0.5])
67+
plt.title('Custom Limits')
68+
plt.grid(True, alpha=0.3)
69+
70+
# Subplot 2: Equal aspect ratio
71+
plt.subplot(1, 3, 2)
72+
plt.plot(x, y)
73+
plt.axis('equal')
74+
plt.title('Equal Scaling')
75+
plt.grid(True, alpha=0.3)
76+
77+
# Subplot 3: Axis turned off
78+
plt.subplot(1, 3, 3)
79+
plt.plot(x, y)
80+
plt.axis('off')
81+
plt.title('Hidden Axes')
82+
83+
plt.tight_layout()
84+
plt.show()
85+
```
86+
87+
The output of this code is:
88+
89+
![Output of matplotlib.pyplot.axis() method example 1](https://raw.githubusercontent.com/Codecademy/docs/main/media/matplotlib-axis-example1.png)
90+
91+
## Example 2: Getting and Setting Axis Limits
92+
93+
This example demonstrates how to set custom axis limits and retrieve the current limits. The `axis()` function is called with a list of four values to set the x and y axis ranges, then called without arguments to return the current limits as a tuple.
94+
95+
```py
96+
import matplotlib.pyplot as plt
97+
import numpy as np
98+
99+
# Create data
100+
x = np.linspace(0, 2*np.pi, 100)
101+
y = np.sin(x)
102+
103+
# Create plot
104+
plt.plot(x, y, linewidth=2)
105+
plt.title('Sine Wave with Custom Axes')
106+
107+
# Set custom axis limits
108+
plt.axis([0, 2*np.pi, -1.5, 1.5])
109+
110+
# Get and print current axis limits
111+
limits = plt.axis()
112+
print(f"Current axis limits: {limits}")
113+
114+
plt.grid(True, alpha=0.3)
115+
plt.show()
116+
```
117+
118+
The output of this code is:
119+
120+
![Output of matplotlib.pyplot.axis() method example 2](https://raw.githubusercontent.com/Codecademy/docs/main/media/matplotlib-axis-example2.png)
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
---
2+
Title: '.figure()'
3+
Description: 'Creates a new figure window or activates an existing one for plotting.'
4+
Subjects:
5+
- 'Data Science'
6+
- 'Data Visualization'
7+
Tags:
8+
- 'Charts'
9+
- 'Graphs'
10+
- 'Matplotlib'
11+
CatalogContent:
12+
- 'learn-python-3'
13+
- 'paths/data-science'
14+
---
15+
16+
The **`.figure()`** function in Matplotlib creates a new top-level container, called a figure, which acts as the canvas for all plots and axes in Matplotlib. If a figure with the given identifier already exists, it makes that figure active instead.
17+
18+
## Syntax
19+
20+
```pseudo
21+
matplotlib.pyplot.figure(
22+
num=None,
23+
figsize=None,
24+
dpi=None,
25+
facecolor=None,
26+
edgecolor=None,
27+
frameon=True,
28+
FigureClass=<class 'matplotlib.figure.Figure'>,
29+
clear=False,
30+
**kwargs
31+
)
32+
```
33+
34+
**Parameters:**
35+
36+
- `num` (int or str, optional): Identifier for the figure. If the number or name already exists, that figure becomes active; otherwise, a new one is created.
37+
- `figsize` (tuple, optional): Width and height of the figure in inches, e.g. `(8, 6)`.
38+
- `dpi` (float, optional): Dots per inch; controls the resolution of the figure.
39+
- `facecolor` (color, optional): Background color of the figure.
40+
- `edgecolor` (color, optional): Border color of the figure.
41+
- `frameon` (bool, default: True): Whether to draw the figure frame.
42+
- `FigureClass` (`Figure` subclass, optional): The class used to create the figure instance. Defaults to `matplotlib.figure.Figure`.
43+
- `clear` (bool, default: False): If `True`, clears the existing figure before reusing it.
44+
- `**kwargs`: Additional parameters passed to the `Figure` constructor.
45+
46+
**Return value:**
47+
48+
Returns a `Figure` object, which is the main container that holds all plot elements like axes, titles, labels, and legends.
49+
50+
## Example
51+
52+
This example creates a new figure canvas with a specific size and background color, then adds a simple sine wave plot to it:
53+
54+
```py
55+
import matplotlib.pyplot as plt
56+
import numpy as np
57+
58+
x = np.linspace(0, 2 * np.pi, 100)
59+
y = np.sin(x)
60+
61+
plt.figure(figsize=(8, 4), facecolor='lightblue')
62+
ax = plt.subplot(1, 1, 1)
63+
ax.plot(x, y)
64+
ax.set_title('Simple Sine Wave')
65+
ax.set_xlabel('X-axis')
66+
ax.set_ylabel('Y-axis')
67+
68+
plt.show()
69+
```
70+
71+
The output of this code is:
72+
73+
![Output of matplotlib.pyplot.figure() method example](https://raw.githubusercontent.com/Codecademy/docs/main/media/figure_example.png)
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
---
2+
Title: '.dot()'
3+
Description: 'Computes the dot product of two arrays.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Linear Algebra'
10+
- 'Methods'
11+
- 'NumPy'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`.dot()`** method computes the dot product of an array with another array or scalar. For one-dimensional arrays, it calculates the standard inner product of vectors. When applied to two-dimensional arrays, it performs matrix multiplication. For arrays with higher dimensions, it executes a sum-product over the last axis of the first array and the second-to-last axis of the second array.
18+
19+
## Syntax
20+
21+
```pseudo
22+
ndarray.dot(b, out=None)
23+
```
24+
25+
**Parameters:**
26+
27+
- `ndarray`: The first array (A) in the dot product operation (A $\cdot$ B).
28+
- `b`: The second array (B) or scalar in the dot product operation.
29+
- `out` (optional): An alternative output array to place the result in. It must have the same shape and buffer length as the expected output, but the type will be cast if necessary.
30+
31+
**Return value:**
32+
33+
Returns the dot product as a scalar, 2-D array, or ndarray, depending on the input dimensions.
34+
35+
## Example
36+
37+
This example shows how to use the `.dot()` method for matrix multiplication between two 2D NumPy arrays, `matrix_a` and `matrix_b`:
38+
39+
```py
40+
# Import NumPy
41+
import numpy as np
42+
43+
# Create the first 2x3 matrix
44+
matrix_a = np.array([[1, 2, 3],
45+
[4, 5, 6]])
46+
47+
# Create the second 3x2 matrix
48+
matrix_b = np.array([[7, 8],
49+
[9, 10],
50+
[11, 12]])
51+
52+
# Use the '.dot()' method for matrix multiplication (2x3 @ 3x2 = 2x2)
53+
result_matrix = matrix_a.dot(matrix_b)
54+
55+
print("Matrix A:")
56+
print(matrix_a)
57+
print("\nMatrix B:")
58+
print(matrix_b)
59+
print("\nResult (A.dot(B)):")
60+
print(result_matrix)
61+
```
62+
63+
The output of the above code will be:
64+
65+
```shell
66+
Matrix A:
67+
[[1 2 3]
68+
[4 5 6]]
69+
70+
Matrix B:
71+
[[ 7 8]
72+
[ 9 10]
73+
[11 12]]
74+
75+
Result (A.dot(B)):
76+
[[ 58 64]
77+
[139 154]]
78+
```
79+
80+
## Codebyte Example
81+
82+
In the following codebyte example, the `.dot()` method is used to calculate the inner product (dot product) of two one-dimensional vectors, `vector_x` and `vector_y`:
83+
84+
```codebyte/python
85+
import numpy as np
86+
87+
# Create two 1-D arrays (vectors)
88+
vector_x = np.array([1, 2, 3])
89+
vector_y = np.array([5, 6, 7])
90+
91+
# Calculate the inner product (dot product)
92+
dot_product = vector_x.dot(vector_y)
93+
94+
print(f"Vector x: {vector_x}")
95+
print(f"Vector y: {vector_y}")
96+
print(f"Dot product (x.dot(y)): {dot_product}")
97+
```
98+
99+
Calculation breakdown:
100+
101+
$$\vec{x} \cdot \vec{y} = (1 \times 5) + (2 \times 6) + (3 \times 7) = 5 + 12 + 21 = 38$$
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
---
2+
Title: '.nbytes'
3+
Description: 'Returns the total number of bytes consumed by the elements of the array.'
4+
Subjects:
5+
- 'Code Foundations'
6+
- 'Computer Science'
7+
Tags:
8+
- 'Arrays'
9+
- 'Attributes'
10+
- 'Memory'
11+
- 'NumPy'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`.nbytes`** attribute returns the total number of bytes consumed by the elements of a [NumPy array](https://www.codecademy.com/resources/docs/numpy/ndarray). This value is calculated as the product of the number of elements in the array (given by `.size`) and the number of bytes per element (given by `.itemsize`).
18+
19+
## Syntax
20+
21+
```pseudo
22+
ndarray.nbytes
23+
```
24+
25+
**Parameters:**
26+
27+
The `.nbytes` attribute takes no parameters.
28+
29+
**Return value:**
30+
31+
Returns an integer representing the total number of bytes consumed by the array elements.
32+
33+
## Example
34+
35+
The following example creates a one-dimensional NumPy array `arr` with 12 elements. The `.nbytes` attribute reports the total bytes used by all array elements. On a 64-bit system where the default integer type (`int64`) uses 8 bytes per element, $12 \text{ elements} \times 8 \text{ bytes}/\text{element} = 96 \text{ bytes}$:
36+
37+
```py
38+
# Import NumPy
39+
import numpy as np
40+
41+
# Create a NumPy array with 12 elements (default type is usually int64, or 8 bytes per item)
42+
arr = np.arange(12)
43+
44+
# Use the '.nbytes' attribute
45+
total_bytes_nbytes = arr.nbytes
46+
47+
print(f"Array: {arr}")
48+
print(f"Bytes per element (.itemsize): {arr.itemsize}")
49+
print(f"Total number of elements (.size): {arr.size}")
50+
print(f"Total bytes consumed (.nbytes): {total_bytes_nbytes}")
51+
```
52+
53+
The result will be similar to the following (the value of `arr.itemsize` might vary based on system architecture):
54+
55+
```shell
56+
Array: [ 0 1 2 3 4 5 6 7 8 9 10 11]
57+
Bytes per element (.itemsize): 8
58+
Total number of elements (.size): 12
59+
Total bytes consumed (.nbytes): 96
60+
```
61+
62+
## Codebyte Example
63+
64+
The example below demonstrates a two-dimensional NumPy array `arr` with a specified data type (`float32`). Since `float32` uses 4 bytes per element and the array contains $2 \times 3 = 6$ elements, the total memory consumed is $6 \times 4 = 24$ bytes:
65+
66+
```codebyte/python
67+
import numpy as np
68+
69+
# Create a 2x3 array of type float32 (4 bytes per element)
70+
arr = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32)
71+
72+
print(f"Array shape: {arr.shape}")
73+
print(f"Array data type: {arr.dtype}")
74+
print(f"Bytes per element (.itemsize): {arr.itemsize}")
75+
print(f"Bytes consumed by elements (.nbytes): {arr.nbytes}")
76+
```

0 commit comments

Comments
 (0)