

# Coordinate systems and transformations



Coordinate systems are a way to represent points in space using numbers. The most common coordinate systems are:

- Cartesian coordinates: This is the most common coordinate system, where points are represented by their x and y coordinates.

- Polar coordinates: This coordinate system uses an angle and a distance from a reference point to represent points.

To transform between these coordinate systems, you can use the following formulas:

- To convert Cartesian coordinates (x, y) to polar coordinates (r, θ):

  $$
  r = \sqrt{x^2 + y^2}
  $$

  $$
  θ = \arctan\left(\frac{y}{x}\right)
  $$

- To convert polar coordinates (r, θ) to Cartesian coordinates (x, y):

  $$
  x = r\cos(θ)
  $$

  $$
  y = r\sin(θ)
  $$

Consider the point (3, 4) in Cartesian coordinates. To convert it to polar coordinates, you can use the formulas above:

- r = $\sqrt{3^2 + 4^2} = \sqrt{25} = 5$

- θ = $\arctan\left(\frac{4}{3}\right) \approx 53.13^\circ$

So, the point (3, 4) in polar coordinates is (5, 53.13°).

## Exercise
Convert the following points from Cartesian coordinates to polar coordinates:

- (0, 0)
- (1, 1)
- (2, 2)
- (3, 3)

To visualize these transformations using matplotlib, you can use the `plot` function to create a scatter plot of the points in the Cartesian coordinate system and then use the `polar` function to create a polar plot of the points.

Here's an example of how to create a scatter plot of the points (0, 0), (1, 1), (2, 2), and (3, 3) in the Cartesian coordinate system:

```python
import matplotlib.pyplot as plt

points = [(0, 0), (1, 1), (2, 2), (3, 3)]

plt.scatter(*zip(*points))
plt.xlabel('x')
plt.ylabel('y')
plt.title('Cartesian Coordinate System')
plt.show()
```

And here's an example of how to create a polar plot of the points (0, 0), (1, 1), (2, 2), and (3, 3):

```python
import numpy as np

r = np.array([0, 1, 2, 3])
theta = np.radians(np.array([0, 45, 90, 135]))

plt.polar(theta, r)
plt.title('Polar Coordinate System')
plt.show()
```

# Plotting shapes and lines



To plot a line in matplotlib, you can use the `plot` function. For example, to plot the line y = 2x, you can use the following code:

```python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-10, 10, 100)
y = 2 * x

plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Line: y = 2x')
plt.show()
```

To plot a circle in matplotlib, you can use the `plot` function with a parametric equation. For example, to plot a circle with radius 3 centered at (0, 0), you can use the following code:

```python
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 2 * np.pi, 100)
x = 3 * np.cos(t)
y = 3 * np.sin(t)

plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Circle: radius = 3')
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
```

## Exercise
Plot the following shapes using matplotlib:

- A parabola: y = x^2
- A hyperbola: y = 1/x
- An ellipse: y = 3/2 * x

# Adding labels and annotations



To add labels to your plots, you can use the `xlabel`, `ylabel`, and `title` functions. For example, to add labels to the x and y axes and a title to the plot, you can use the following code:

```python
import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3], [0, 1, 4, 9])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot: y = x^2')
plt.show()
```

To add annotations to your plots, you can use the `text` function. For example, to add an annotation to the point (1, 1) on the plot, you can use the following code:

```python
import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3], [0, 1, 4, 9])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot: y = x^2')
plt.text(1, 1, '(1, 1)', fontsize=10, ha='right', va='bottom')
plt.show()
```

## Exercise
Add labels and annotations to the following plots:

- A plot of the function y = 2x.
- A plot of the circle with radius 3 centered at (0, 0).
- A plot of the parabola y = x^2.

# Customizing colors and styles



To customize the colors and styles of your plots, you can use various keyword arguments to the `plot` function. For example, to change the color and line style of a plot, you can use the following code:

```python
import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3], [0, 1, 4, 9], color='red', linestyle='--')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot: y = x^2')
plt.show()
```

To customize the colors and styles of annotations, you can use the `text` function with the `color`, `fontsize`, `ha`, and `va` keyword arguments. For example, to change the color and alignment of an annotation, you can use the following code:

```python
import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3], [0, 1, 4, 9])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot: y = x^2')
plt.text(1, 1, '(1, 1)', fontsize=10, ha='right', va='bottom', color='green')
plt.show()
```

## Exercise
Customize the colors and styles of the following plots:

- A plot of the function y = 2x.
- A plot of the circle with radius 3 centered at (0, 0).
- A plot of the parabola y = x^2.

# Creating interactive visualizations



To create interactive visualizations, you can use the `plotly` library, which provides a higher-level interface for creating interactive plots. For example, to create an interactive scatter plot of the points (0, 0), (1, 1), (2, 2), and (3, 3), you can use the following code:

```python
import plotly.express as px

points = [(0, 0), (1, 1), (2, 2), (3, 3)]

fig = px.scatter(x=[x for x, y in points], y=[y for x, y in points])
fig.show()
```

## Exercise
Create interactive visualizations of the following plots:

- A plot of the function y = 2x.
- A plot of the circle with radius 3 centered at (0, 0).
- A plot of the parabola y = x^2.

# Working with different plot types



To create a bar plot in matplotlib, you can use the `bar` function. For example, to create a bar plot of the data [1, 2, 3, 4], you can use the following code:

```python
import matplotlib.pyplot as plt

data = [1, 2, 3, 4]

plt.bar(range(len(data)), data)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Bar Plot')
plt.show()
```

To create a histogram in matplotlib, you can use the `hist` function. For example, to create a histogram of the data [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], you can use the following code:

```python
import matplotlib.pyplot as plt

data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

plt.hist(data, bins=range(min(data), max(data) + 2), align='left')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Histogram')
plt.show()
```

To create a box plot in matplotlib, you can use the `boxplot` function. For example, to create a box plot of the data [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], you can use the following code:

```python
import matplotlib.pyplot as plt

data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

plt.boxplot(data)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Box Plot')
plt.show()
```

## Exercise
Create the following plots using matplotlib:

- A bar plot of the data [1, 2, 3, 4].
- A histogram of the data [1, 2, 2, 3, 3, 3, 4, 4, 4, 4].
- A box plot of the data [1, 2, 2, 3, 3, 3, 4, 4, 4, 4].

# Advanced transformations and projections



To visualize advanced transformations and projections in matplotlib, you can use the `transforms` module to create custom coordinate transformations. For example, to create a plot of the function y = x^2 and apply a custom transformation that scales the x-axis by a factor of 2 and the y-axis by a factor of 3, you can use the following code:

```python
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

x = np.linspace(-10, 10, 100)
y = x**2

trans = transforms.Affine2D().scale(2, 3)

plt.plot(x, y)
plt.gca().get_xaxis_transform().transform(x)
plt.gca().get_yaxis_transform().transform(y)
plt.gca().set_transform(trans + plt.gca().get_transform())
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot: y = x^2 (Scaled)')
plt.show()
```

## Exercise
Visualize the following transformations using matplotlib:

- A plot of the function y = x^2 with a custom transformation that scales the x-axis by a factor of 2 and the y-axis by a factor of 3.
- A plot of the circle with radius 3 centered at (0, 0) with a custom transformation that rotates the plot by 45 degrees.
- A plot of the parabola y = x^2 with a custom transformation that reflects the plot across the x-axis.

# Creating 3D visualizations



To create 3D visualizations in matplotlib, you can use the `mpl_toolkits.mplot3d` module. For example, to create a 3D scatter plot of the points (0, 0, 0), (1, 1, 1), (2, 2, 2), and (3, 3, 3), you can use the following code:

```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

points = [(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3)]

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(*zip(*points))
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.title('3D Scatter Plot')
plt.show()
```

## Exercise
Create the following 3D visualizations using matplotlib:

- A 3D scatter plot of the points (0, 0, 0), (1, 1, 1), (2, 2, 2), and (3, 3, 3).
- A 3D plot of the function z = x^2 + y^2.
- A 3D plot of the sphere with radius 3 centered at (0, 0, 0).

# Creating animations and movies



To create animations and movies in matplotlib, you can use the `animation` module. For example, to create an animation of a circle with radius 3 centered at (0, 0) that rotates around the z-axis, you can use the following code:

```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

def update(frame):
    t = frame * 2 * np.pi / 100
    x = 3 * np.cos(t)
    y = 3 * np.sin(t)
    z = 0
    ax.clear()
    ax.plot([x], [y], [z], marker='o', markersize=10, linestyle='None')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.set_title('Rotating Circle')
    ax.set_xlim(-4, 4)
    ax.set_ylim(-4, 4)
    ax.set_zlim(-1, 1)
    ax.view_init(30, frame)

ani = FuncAnimation(fig, update, frames=range(100), interval=50)
plt.show()
```

## Exercise
Create the following animations and movies using matplotlib:

- An animation of a circle with radius 3 centered at (0, 0) that rotates around the z-axis.
- An animation of a sphere with radius 3 centered at (0, 0, 0) that rotates around the z-axis.
- A movie of a plot of the function y = x^2 that zooms in and out.

# Using matplotlib for scientific visualization



To use matplotlib for scientific visualization, you can customize the appearance of your plots using various keyword arguments to the `plot` function, such as `linewidth`, `marker`, `markersize`, and `markeredgewidth`. For example, to create a publication-ready plot of the function y = 2x, you can use the following code:

```python
import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 3], [0, 1, 4, 9], linewidth=2, marker='o', markersize=6, markeredgewidth=2)
plt.xlabel('x', fontsize=14, fontweight='bold')
plt.ylabel('y', fontsize=14, fontweight='bold')
plt.title('Plot: y = x^2', fontsize=16, fontweight='bold')
plt.tick_params(axis='both', which='major', labelsize=12)
plt.show()
```

## Exercise
Create the following publication-ready plots using matplotlib:

- A plot of the function y = 2x.
- A plot of the circle with radius 3 centered at (0, 0).
- A plot of the parabola y = x^2.

# Advanced topics in scientific visualization



To create custom colormaps in matplotlib, you can use the `LinearSegmentedColormap` class. For example, to create a custom colormap that transitions from blue to red, you can use the following code:

```python
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list('custom', ['blue', 'red'])

plt.imshow([[0, 1], [1, 0]], cmap=cmap)
plt.colorbar()
plt.show()
```

To create contour plots in matplotlib, you can use the `pcolormesh` function. For example, to create a contour plot of the function y = x^2, you can use the following code:

```python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-10, 10, 100)
y = x**2

plt.pcolormesh(x, y, cmap='viridis')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Contour Plot: y = x^2')
plt.colorbar()
plt.show()
```

## Exercise
Create the following advanced visualizations using matplotlib:

- A contour plot of the function y = x^2.
- A plot of the sphere with radius 3 centered at (0, 0, 0) with a custom colormap that transitions from blue to red.
- A plot of the parabola y = x^2 with a custom colormap that transitions from blue to red.

# Conclusion

In this textbook, you have learned how to use matplotlib for geometry and visualization. You have learned how to create various types of plots, customize their appearance, create interactive visualizations, and visualize advanced transformations and projections. You have also learned how to create 3D visualizations, animations and movies, and use matplotlib for scientific visualization.

By applying the concepts and techniques learned in this textbook, you will be able to create powerful and informative visualizations to explore and understand your data.