Serie 5 Aufgabe 3. Jedes plot hat eine unterschiedliche Linienfarbe und eine Legende mit der Funktion als Beschreibung

This commit is contained in:
Sandro Zimmermann 2026-10-26 14:06:52 +01:00
parent a973b81707
commit 3a5e413150

View File

@ -1,57 +1,109 @@
#%%
import numpy as np
import matplotlib.pyplot as plt
# Import required libraries
import numpy as np # Numerical operations and array handling
import matplotlib.pyplot as plt # Plotting library
# Initialize figure counter and line width for all plots
fig = 0
lw = 3
functions = [
# Named color palette mapping descriptive names to hex codes
colors = {
"deep blue": "#1f77b4",
"orange": "#ff7f0e",
"green": "#2ca02c",
"red": "#d62728",
"purple": "#9467bd",
"brown": "#8c564b",
}
# List of functions to plot, each with its domain, resolution, callable,
# LaTeX label, and assigned color
plots = [
{
"x_0": 0.,
"x_E": 2.,
"N": 2,
"f": lambda x: 0.4 * x + 1,
"label": r"$f(x) = 0.4\,x + 1$",
"color": colors["deep blue"],
},
{
"x_0": -2.,
"x_E": 2.,
"N": 129,
"f": lambda x: x ** 2,
"label": r"$f(x) = x^2$",
"color": colors["orange"],
},
{
"x_0": -6.,
"x_E": 2.,
"N": 129,
"f": lambda x: 2 ** x,
"label": r"$f(x) = 2^x$",
"color": colors["green"],
},
{
"x_0": 0.01,
"x_E": 10.,
"N": 129,
"f": lambda x: np.log(x)/np.log(10),
"f": lambda x: np.log(x) / np.log(10),
"label": r"$f(x) = \log_{10}(x)$",
"color": colors["red"],
},
{
"x_0": -1,
"x_E": 4,
"N": 129,
"f": lambda x: 3 / (x + 2),
"label": r"$f(x) = \dfrac{3}{x+2}$",
"color": colors["purple"],
},
{
"x_0": 0,
"x_E": 4 * np.pi,
"N": 257,
"f": lambda x: 2 * np.sin(x),
"label": r"$f(x) = 2\,\sin(x)$",
"color": colors["brown"],
},
]
for function in functions:
x_data = np.linspace(function["x_0"], function["x_E"], function["N"])
y_data = function["f"](x_data)
# Loop over each plot definition and create a separate figure
for plot in plots:
# Generate evenly spaced x values over the specified domain
x_data = np.linspace(plot["x_0"], plot["x_E"], plot["N"])
# Evaluate the function at each x point
y_data = plot["f"](x_data)
# Create a new figure for the current plot
fh = plt.figure(fig)
fig += 1
plt.plot(x_data, y_data, linewidth=lw)
# Plot the curve with the assigned color, line width, and LaTeX label
plt.plot(
x_data,
y_data,
linewidth=lw,
color=plot["color"],
label=plot["label"],
)
# Set axis labels
plt.xlabel(r"$x$")
plt.ylabel(r"$y$")
# Display a grid for readability
plt.grid(visible=True)
plt.axis("image")
# Enforce equal scaling on both axes
plt.axis("image")
# Add a legend showing the function expression in LaTeX
plt.legend()
# Display all figures
plt.show()