Skip to content

Commit af52b1b

Browse files
authored
Merge branch 'Codecademy:main' into python-plotly-graph-carpet
2 parents 268371b + e61ed3d commit af52b1b

File tree

19 files changed

+751
-0
lines changed

19 files changed

+751
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
Title: 'Regression'
3+
Description: 'Regression models relationships between variables to predict a dependent variable utilizing one or more independent variables.'
4+
Subjects:
5+
- 'AI'
6+
- 'Data Science'
7+
Tags:
8+
- 'Machine Learning'
9+
- 'Python'
10+
CatalogContent:
11+
- 'learn-python-3'
12+
- 'paths/computer-science'
13+
---
14+
15+
**Regression** is a mathematical process used to model data by identifying a function that best represents its patterns. In machine learning, regression functions are used for predictive analysis.
16+
17+
There are various regression techniques and the choice depends on factors such as data distribution. A simple form is linear regression, represented by the equation:
18+
19+
```
20+
y = a\*x + b
21+
```
22+
23+
Visualizing this equation as a straight line on a 2D graph:
24+
25+
- `y`: The dependent (outcome) variable, plotted on the y-axis (vertical).
26+
- `x`: The independent (predictor) variable, plotted on the x-axis (horizontal).
27+
- `b`: The intercept, representing the value of `y` when `x = 0`.
28+
- `a`: The slope, indicating how `y` changes when `x` increases by one unit.
29+
30+
## Example
31+
32+
The following code predicts a person's weight based on a person's height:
33+
34+
```py
35+
import pandas as pd
36+
import statsmodels.api as sm
37+
import matplotlib.pyplot as plt
38+
39+
# Sample data
40+
heights = [150, 152, 160, 172, 176, 176, 180, 189]
41+
weights = [50, 65, 65, 70, 80, 90, 90, 89]
42+
43+
# Create a DataFrame
44+
measurements = pd.DataFrame({'height': heights, 'weight': weights})
45+
46+
# Fit the linear regression model
47+
model = sm.OLS.from_formula("weight ~ height", data=measurements)
48+
results = model.fit()
49+
50+
# Print the summary of the model
51+
print(results.summary())
52+
53+
# Plot the data and the regression line
54+
plt.scatter(measurements['height'], measurements['weight'], label='Data')
55+
plt.plot(measurements['height'], results.predict(measurements), color='red', label='Regression Line')
56+
plt.xlabel('Height (cm)')
57+
plt.ylabel('Weight (kg)')
58+
plt.title('Height vs Weight with Regression Line')
59+
plt.legend()
60+
61+
# Save the plot as an image file
62+
plt.savefig('height-vs-weight-plot.png')
63+
64+
# Show the plot
65+
plt.show()
66+
```
67+
68+
This code performs linear regression using `statsmodels` to analyze the relationship between height and weight. It fits a model of the form `weight = a * height + b`, prints the regression summary, and visualizes the data with a scatter plot and a best-fit line.
69+
70+
The output of this code is as follows:
71+
72+
![The output for the above example](https://raw.githubusercontent.com/Codecademy/docs/main/media/height-vs-weight-plot.png)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
---
2+
Title: '.getElementById()'
3+
Description: 'Retrieve the first HTML element with the specified id, returning null if no match is found.'
4+
Subjects:
5+
- 'Web Development'
6+
- 'Web Design'
7+
Tags:
8+
- 'DOM'
9+
- 'Elements'
10+
- 'JavaScript'
11+
- 'Methods'
12+
CatalogContent:
13+
- 'introduction-to-javascript'
14+
- 'paths/front-end-engineer-career-path'
15+
---
16+
17+
The **`.getElementById()`** method is a commonly used function in the Document Object Model (DOM) that allows developers to retrieve an HTML element by its `id` attribute. This method is part of the `document` object and returns the first element that matches the specified `id`. If no element is found, it returns `null`.
18+
19+
## Key Characteristics
20+
21+
- **Fast and efficient**: Since IDs are unique, this method quickly retrieves elements without searching the entire DOM.
22+
- **Returns a single element**: It always returns one element (or `null` if not found).
23+
- **Case-sensitive**: The provided `id` must match exactly, including letter casing.
24+
25+
> **Note**: If multiple elements share the same `id` (which is invalid HTML), `getElementById()` still returns only the first match.
26+
27+
## Syntax
28+
29+
```pseudo
30+
document.getElementById("elementId");
31+
```
32+
33+
- `elementId` (string): The `id` of the element to retrieve.
34+
35+
## Example
36+
37+
The following example demonstrates the usage of the `.getElementById()` method:
38+
39+
```html
40+
<!DOCTYPE html>
41+
<html lang="en">
42+
<head>
43+
<title>getElementById Example</title>
44+
</head>
45+
<body>
46+
<p id="demo">Hello, World!</p>
47+
<button onclick="changeText()">Click Me</button>
48+
49+
<script>
50+
function changeText() {
51+
let element = document.getElementById('demo');
52+
element.innerHTML = 'Text changed!';
53+
}
54+
</script>
55+
</body>
56+
</html>
57+
```
58+
59+
In this example, the `getElementById("demo")` function retrieves the `<p>` element with `id="demo"` and the `innerHTML` property is updated when the button is clicked.
60+
61+
The output will look like:
62+
63+
![A webpage with a paragraph displaying "Hello, World!" and a button labeled "Click Me", when clicked, the text changes to "Text changed!".](https://raw.githubusercontent.com/Codecademy/docs/main/media/get-element-by-id-example.gif)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
---
2+
Title: '.innerHTML'
3+
Description: 'Sets or fetches the HTML content inside an element in the DOM.'
4+
Subjects:
5+
- 'Web Development'
6+
- 'Web Design'
7+
Tags:
8+
- 'DOM'
9+
- 'ES6'
10+
- 'Properties'
11+
- 'Strings'
12+
CatalogContent:
13+
- 'introduction-to-javascript'
14+
- 'paths/front-end-engineer-career-path'
15+
---
16+
17+
The **`.innerHTML`** property in JavaScript is a fundamental DOM (Document Object Model) manipulation tool that allows setting or retrieving the HTML content inside an element. It allows developers to dynamically modify a webpage's content by reading or writing HTML markup as a string. When setting `.innerHTML`, the browser parses the provided string as HTML and updates the DOM accordingly. This property is particularly useful for inserting multiple elements or complex HTML structures at once.
18+
19+
## Syntax
20+
21+
```pseudo
22+
// Getting HTML content
23+
const content = element.innerHTML;
24+
25+
// Setting HTML content
26+
element.innerHTML = htmlString;
27+
```
28+
29+
- `element`: The DOM element whose content is being accessed or modified.
30+
- `htmlString`: A string containing HTML markup to be injected.
31+
32+
When reading `.innerHTML`, it returns the current HTML string inside the element.
33+
34+
### Notes
35+
36+
- Setting `.innerHTML` replaces all existing content within the element.
37+
- The provided HTML string is parsed and valid HTML tags are converted to DOM elements.
38+
- Be cautious with user-provided content as `.innerHTML` can execute scripts, making it vulnerable to XSS (Cross-Site Scripting) attacks.
39+
- For plain text content, consider using `.textContent` for better security and performance.
40+
- If an element contains event handlers, replacing `.innerHTML` will remove them. Consider `.appendChild()` for better control.
41+
42+
## Example
43+
44+
Here's how to use `.innerHTML` to modify content in a `<div>`:
45+
46+
```js
47+
// Select the <div> element with the id 'container'
48+
const container = document.getElementById('container');
49+
50+
// Set new HTML content
51+
container.innerHTML = '<p>This paragraph was added using innerHTML!</p>';
52+
53+
// Get the current HTML content
54+
console.log(container.innerHTML); // "<p>This paragraph was added using innerHTML!</p>"
55+
56+
// Replace with more complex HTML
57+
container.innerHTML = `
58+
<h2>Dynamic Content</h2>
59+
<p>First paragraph</p>
60+
<ul>
61+
<li>Item 1</li>
62+
<li>Item 2</li>
63+
</ul>
64+
`;
65+
```
66+
67+
The above code produces the following output:
68+
69+
```shell
70+
"<p>This paragraph was added using innerHTML!</p>"
71+
```
72+
73+
After execution, the `<div>` will contain:
74+
75+
```html
76+
<div id="container">
77+
<h2>Dynamic Content</h2>
78+
<p>First paragraph</p>
79+
<ul>
80+
<li>Item 1</li>
81+
<li>Item 2</li>
82+
</ul>
83+
</div>
84+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
Title: '.replaceChildren()'
3+
Description: 'Replaces all child nodes of an element with new nodes or clears them if no arguments are provided.'
4+
Subjects:
5+
- 'Web Development'
6+
- 'Web Design'
7+
Tags:
8+
- 'Arguments'
9+
- 'DOM'
10+
- 'ES6'
11+
- 'Functions'
12+
CatalogContent:
13+
- 'introduction-to-javascript'
14+
- 'paths/front-end-engineer-career-path'
15+
---
16+
17+
The **`.replaceChildren()`** method in JavaScript is a modern DOM manipulation method that replaces all child nodes of an element with new specified nodes or clears them if no arguments are provided.
18+
19+
Unlike older methods such as `.innerHTML` or [`.removeChild()`](https://www.codecademy.com/resources/docs/javascript/dom-manipulation/removeChild), `.replaceChildren()` provides a cleaner, more efficient, and safer way to update the contents of an element without unnecessary parsing or manipulation overhead.
20+
21+
This method is particularly useful when dynamically updating UI elements, such as replacing a list of items, updating content sections, or efficiently clearing an element's children without affecting event listeners on the parent.
22+
23+
## Key Characteristics
24+
25+
- More efficient than manually removing and appending children.
26+
- Accepts multiple nodes or strings as arguments.
27+
- Works similarly to `.innerHTML = ""` for clearing, but safer as it avoids HTML parsing.
28+
29+
## Syntax
30+
31+
```pseudo
32+
element.replaceChildren(...nodes);
33+
```
34+
35+
- `nodes` (optional): One or more nodes or strings to insert as new children. If no arguments are provided, all child nodes are removed.
36+
37+
## Example
38+
39+
The following example demonstrates the usage of the `.replaceChildren()` method:
40+
41+
```html
42+
<!DOCTYPE html>
43+
<html lang="en">
44+
<head>
45+
<title>replaceChildren Example</title>
46+
</head>
47+
<body>
48+
<div id="container">
49+
<p>Old content</p>
50+
</div>
51+
<button onclick="updateContent()">Replace Content</button>
52+
53+
<script>
54+
function updateContent() {
55+
let container = document.getElementById('container');
56+
let newParagraph = document.createElement('p');
57+
newParagraph.textContent = 'New content added!';
58+
container.replaceChildren(newParagraph);
59+
}
60+
</script>
61+
</body>
62+
</html>
63+
```
64+
65+
In this example, the `.replaceChildren()` removes the existing `<p>` inside `#container` and replaces it with a new one. If called without arguments, it clears all children.
66+
67+
The output will be:
68+
69+
![A div showing "Old content" updates to "New content added!" when the button is clicked.](https://raw.githubusercontent.com/Codecademy/docs/main/media/replace-children-example.gif)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
---
2+
Title: '.Contour()'
3+
Description: 'Creates a contour plot, which represents 3D surface data in 2D using contour lines or filled color regions to show variations in value.'
4+
Subjects:
5+
- 'Data Science'
6+
- 'Data Visualization'
7+
Tags:
8+
- 'Data'
9+
- 'Data Structures'
10+
- 'Functions'
11+
- 'Plotly'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/data-science'
15+
---
16+
17+
In Plotly, the **`.Contour()`** function creates a contour plot, which represents 3D surface data in a 2D projection using contour lines or filled color regions. This function is useful for visualizing gradual variations in a dataset over a 2D plane, such as temperature distributions, elevation maps, and probability density functions.
18+
19+
## Syntax
20+
21+
```pseudo
22+
plotly.graph_objects.Contour(z=None, x=None, y=None, colorscale=None, contours=None, ...)
23+
```
24+
25+
- `z`: A 2D array (list or [NumPy array](https://www.codecademy.com/resources/docs/numpy/ndarray)) representing the values to be contoured.
26+
- `x`: A 1D or 2D array defining the x-coordinates corresponding to `z` values.
27+
- `y`: A 1D or 2D array defining the y-coordinates corresponding to `z` values.
28+
- `colorscale`: Defines the color scheme of the contour plot (e.g., `"Viridis"`, `"Jet"`, etc.).
29+
- `contours`: Controls the contour levels with a dictionary containing:
30+
- `start`: The starting value of the contours.
31+
- `end`: The ending value of the contours.
32+
- `size`: The step size between contour levels.
33+
34+
> **Note:** The ellipsis (...) in the syntax indicates that there can be additional optional parameters beyond those listed here.
35+
36+
## Example
37+
38+
The following example demonstrates the usage of the `.Contour()` function:
39+
40+
```py
41+
import plotly.graph_objects as go
42+
43+
# Define x and y coordinates
44+
x = [-2, -1, 0, 1, 2]
45+
y = [-2, -1, 0, 1, 2]
46+
47+
# Define a 2D list for z values
48+
z = [[0.1, 0.2, 0.3, 0.2, 0.1],
49+
[0.2, 0.4, 0.6, 0.4, 0.2],
50+
[0.3, 0.6, 1.0, 0.6, 0.3],
51+
[0.2, 0.4, 0.6, 0.4, 0.2],
52+
[0.1, 0.2, 0.3, 0.2, 0.1]]
53+
54+
# Create a contour plot
55+
fig = go.Figure(data=[go.Contour(z=z, # Data values for contour levels
56+
x=x, # X-coordinates
57+
y=y, # Y-coordinates
58+
colorscale="Viridis", # Color scheme
59+
contours=dict(start=0, end=1, size=0.1))]) # Define contour levels
60+
61+
# Display the plot
62+
fig.show()
63+
```
64+
65+
The above code generates the following output:
66+
67+
![The output for the above example](https://raw.githubusercontent.com/Codecademy/docs/main/media/contour-plot.png)

0 commit comments

Comments
 (0)