---
# System prepended metadata

title: Matplotlib and Seaborn

---

# Matplotlib and Seaborn 


### Anotomy of a figure 

https://matplotlib.org/stable/gallery/showcase/anatomy.html

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


### Figure and plots 
```python=1
fig = plt.figure(figsize=(20, 8))
ax1, ax2= fig.subplots(1, 2)      # Create multiple plots
ax = fig.subplots()               # Create single plot
fig.savefig('file_name.pdf')      # Save figure to a pdf file
```

### Axis 

- Axis / limits: https://matplotlib.org/stable/api/axes_api.html#axis-limits
- Ticks and tick labels: https://matplotlib.org/stable/api/axes_api.html#ticks-and-tick-labels


```python=
font = {
    'family': 'serif',
    'color': 'darkred',
    'weight': 'normal',
    'size': 24,
}
# label-related 
ax.set_xlabel(None)                      # remove x-axis label 
ax.set_xlabel("X label", fontdict=font)  # set label with font
ax.set_xlabel("X label", fontsize=14)    # set label with fontsize
ax.set_xlabel("X label", labelpad=4.0)   # adjust the label offset/position

# title-related
ax.set_title("title", fontdict=font)
ax.set_title("title", loc="left")        # loc : {"center", "left", "right"}
ax.set_title("title", pad=4.)            # adjust the title offset/position

# tick-realted 
ticks = ax.get_xticks()
ax.set_xticks(ticks, labels=None)        # set major ticks 
ax.set_xticks(ticks, minor=True)         # set minor ticks 

ax.set_xticklabels(labels, fontdict=font)# set major tick labels
ax.set_xticklabels(labels, minor=True)   # set minor tick labels

# scale
ax.set_xscale("log")                     # log-scale axis
```

### Legend 
```python=
l = ax.get_legend()
l.remove()                               # remove legend
l.set_title(None)                        # remove title 
l.set_title('legend', fontdict=font)     # set legend title 

# edit legend
texts = l.get_texts()
for txt in texts:
    label = txt.get_text()
    if '-' in label:
        label = r'{}'.format(label.replace('-', '$-$'))
    txt.set_text(label)
    txt.set_family(font['family'])
    txt.set_fontsize(font['size'])
l.set_frame_on(False)                    # remove legend frame
```

