---
# System prepended metadata

title: Plotting with matplotlib
tags: [Python Cheatbook]

---

---
title: Plotting with matplotlib
tags: Python Cheatbook
---

# Plotting with `matplotlib`

The general idea when plotting with `matplotlib` is that it is usually done in steps.
1. Initiaize plot, example `plt.scatter(x,y)` -- initialized within `plt`, there is no return object.
2. Configure the plot, example `plt.axis('off')`
3. Render the plot, example `plt.show()` ==always call it to view the plot==, alternative is to save the plot to a file instead with `plt.savefig(path)`. **Note** that calling `show` before `savefig` will result in a blank canvas.

## Scatter plots
```python=
import matplotlib.pyplot as plt

#create data
x = [25, 12, 15, 14, 19, 23, 25, 29]
y = [5, 7, 7, 9, 12, 9, 9, 4]

#create scatterplot
plt.scatter(x, y, s=200)

plt.show()
```

**Note**: plot shown below is *not* from example code above.

![](https://i.imgur.com/KPejmz4.png)

## General config of plots


Remove the ticks but keep the box
```python=
plt.tick_params(left=False,         # remove left ticks
                bottom=False,       # remove bottom ticks
                labelleft=False,    # remove left labels
                labelbottom=False)  # remove bottom labels

plt.show()
```

![](https://i.imgur.com/8AXN1u5.png)


Remove everything around the image or plot

```python
plt.axis('off')
```
![](https://i.imgur.com/nteZD5D.png)

Add a background image to the plot
```python=
img_path = './background.png'
plt.imshow(plt.imread(img_path), zorder=-1)
```

## References

1. https://www.statology.org/matplotlib-remove-ticks/
2. https://www.labri.fr/perso/nrougier/scientific-visualization.html -- open access book on scientific visualizations. 