# Matplotlib Also refers to official cheatsheat [here](https://matplotlib.org/cheatsheets/) <center><img src="https://drive.google.com/uc?id=1zKJuabAWhclAXqLNr-usOpQC_WRiFgnP" width="70%" height="70%"></center> <br/> <br/> <div align="center"> | Functional | OOP | |:-----------:|:-------------:| | plt.xlabel() | ax.set_xlabel() | | plt.ylabel() | ax.set_ylabel() | | plt.xlim() | ax.set_xlim() | | plt.ylim() | ax.set_ylim() | | plt.title() | ax.set_title() | </div> ## 1. General procedure for plotting To create a 2D line plot, follow these general steps: 1. Call the `plt.figure()` to create a new figure. (optional for `%matplotlib inline`) 2. Generate a sequence of $x$ values usually using `linspace()`. 3. Generate a sequence of $y$ values usually by substitute the x values into a function. 4. Input `plt.plot(x, y, [format], **kwargs)` where `[format]` is an (optional) format string, and `**kwargs` are (optional) keyword arguments specifying the line properties of the plot. 5. Utilize `plt` functions to enhance the figure with features such as a title, legend, grid lines, etc. 6. Input `plt.show()` to display the resulting figure (this step is optional in a Jupyter notebook). ## 2. Plots <a name="plots"></a> ### Creating plots *Figure* <a name="figure"></a> | Operator | Description | Documentation | | :------------- | :------------- | :----------- | | `fig = plt.figures()` | a container that contains all plot elements | [link](https://matplotlib.org/stable/api/figure_api.html) | *Axes* <a name="axes"></a> | Operator | Description | Documentation | | :------------- | :------------- | :----------- | | `fig.add_axes()`<br/>`a = fig.add_subplot(222)` |Initializes subplot <br/> A subplot is an axes on a grid system <br/> row-col-num | [link](https://matplotlib.org/stable/api/figure_api.html)| | `fig, b = plt.subplots(nrows=3, nclos=2)`|Adds subplot| [link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html)| |`ax = plt.subplots(2, 2)`|Creates subplot|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html)| ### Plotting <a name="1d"></a> *1D Data* <a name="plotting"></a> | Operator | Description | Documentation | | :------------- | :------------- | :----------- | | `lines = plt.plot(x,y)`|Plot data connected by lines|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html)| | `plt.scatter(x,y)`|Creates a scatterplot, unconnected data points|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html)| |`plt.hist(x, y)`|Plots a histogram|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html)| |`plt.fill_between(x,y,color='yellow')`|Fill area under/between plots|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.fill_between.html)| *Saving plots* <a name="save"></a> | Operator | Description | Documentation | | :------------- | :------------- | :----------- | |`plt.savefig('pic.png')`|Saves plot/figure to image|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html)| ### Customization <a name="custom"></a> *Color* <a name="colors"></a> | Operator | Description | Documentation | | :------------- | :------------- | :----------- | | `plt.plot(x, y, color='lightblue')`<br/>`plt.plot(x, y, alpha = 0.4)`|colors plot to color blue|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html)| |`plt.colorbar(mappable, orientation='horizontal')`|`mappable`: the Image, Contourset etc to which colorbar applies|[link](https://matplotlib.org/stable/api/colorbar_api.html)| *Markers* <a name="markers"></a> (see [examples](#examples)) | Operator | Description | Documentation | | :------------- | :------------- | :----------- | | `plt.plot(x, y, marker='*')`|adds `*` for every data point|[link](https://matplotlib.org/stable/api/markers_api.html)| | `plt.scatter(x, y, marker='.')` |adds . for every data point|see above| *Lines* <a name="lines"></a> | Operator | Description | Documentation | | :------------- | :------------- | :----------- | |`plt.plot(x, y, linewidth=2)`|Sets line width|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html)| |`plt.plot(x, y, ls='solid')`|Sets linestyle, `ls` can be ommitted, see 2 below|see above| |`plt.plot(x, y, ls='--')`|Sets linestyle, `ls` can be ommitted, see below|see above| |`plt.plot(x,y,'--', x**2, y**2, '-.')`|Lines are '--' and '_.'|see above| *Text* <a name="text"></a> | Operator | Description | Documentation | | :------------- | :------------- | :----------- | |`plt.text(1, 1,'Example Text',style='italic')`|Places text at coordinates 1/1|[link](https://matplotlib.org/stable/api/text_api.html)| |`ax.annotate('some annotation', xy=(10, 10))`|Annotate the point with coordinates`xy` with text `s`|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html)| |`plt.title(r'$delta_i=20$', fontsize=10)`|Mathtext|[link](https://matplotlib.org/stable/tutorials/text/mathtext.html)| *Limits, Legends/Labels , Layout* <a name="lll"></a> *Limits* | Operator | Description | Documentation | | :------------- | :------------- | :----------- | |`plt.xlim(0, 7)`|Sets x-axis to display 0 - 7 |[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xlim.html)| |`plt.ylim(-0.5, 9)`|Sets y-axis to display -0.5 - 9|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ylim.html)| |`ax.set(xlim=[0, 7], ylim=[-0.5, 9])`<br/>`ax.set_xlim(0, 7)`|| |`plt.axis('equal')`|Set the aspect ratio of the plot to 1|| *Legends/Labels* | Operator | Description | Documentation | | :------------- | :------------- | :----------- | |`plt.title('just a title')`|Sets title of plot|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.title.html)| |`plt.xlabel('x-axis')`|Sets label next to x-axis|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xlabel.html)| |`plt.ylabel('y-axis')`|Sets label next to y-axis|[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ylabel.html)| |`plt.legend(loc='best')`|No overlapping plot elements|[link](https://matplotlib.org/stable/api/legend_api.html)| *Ticks* | Operator | Description | Documentation | | :------------- | :------------- | :----------- | |`plt.xticks(x, labels, rotation='vertical')`| |[link](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xticks.html)| ## 3. Examples <a name="examples"></a> ### Basics <a name="basics"></a> ```python import matplotlib.pyplot as plt x = np.linspace(-2,2,200) plt.plot(x, np.cos(x - 0), color='blue') # specify color by name plt.plot(x, np.cos(x - 1), color='g') # short color code (rgbcmyk) plt.plot(x, np.cos(x - 2), color='0.75') # grayscale between 0 and 1 plt.plot(x, np.cos(x - 4), color=(1.0,0.2,0.3)); # RGB tuple, values 0 to 1 ``` ![](https://hackmd.io/_uploads/Sy9vHxHr2.png) ```python import matplotlib.pyplot as plt plt.plot(x, np.sin(x), '-g', label='sin(x)') # solid green line plt.plot(x, np.cos(x), ':b', label='cos(x)') # dotted blue line plt.title("A Sin/Cos Curve", fontsize=18) # we can also specify the font size plt.xlabel("x", fontsize=14) plt.ylabel("sin(x)", fontsize=14) plt.legend(fontsize=12) plt.axis('equal'); ``` ![](https://hackmd.io/_uploads/B1CRIlHSn.png) ```python import matplotlib.pyplot as plt plt.plot(x, y, '-vb', markersize=15, linewidth=4, markerfacecolor='orange', markeredgewidth=2) plt.ylim(-1.2, 1.2); ``` ![](https://hackmd.io/_uploads/Hy4MPlBHn.png) ```python import matplotlib.pyplot as plt plt.hist(data, bins=30, density=True, alpha=0.5, color='steelblue', edgecolor='none') x = np.linspace(-4,4,100) y = 1/(2*np.pi)**0.5 * np.exp(-x**2/2) plt.plot(x,y,'b',alpha=0.8); ``` ![](https://hackmd.io/_uploads/SJjEwlSSh.png) ```python import matplotlib.pyplot as plt x = np.linspace(0, 2*np.pi, 1000) plt.plot(x, np.sin(x), 'r') plt.plot(x, np.cos(x), 'g') plt.fill_between(x, np.cos(x), np.sin(x), color='red', alpha=0.1); ``` ![](https://hackmd.io/_uploads/BkuvvlHB3.png) ```python import matplotlib.pyplot as plt t = np.linspace(0, 2*np.pi, 64) r = np.sin(t) # plot in polar coordinates plt.axes(projection='polar') plt.plot(t+(r<0)*np.pi, np.abs(r), '-') # Set ticks for polar coordinate plt.xticks([0, np.pi/2, np.pi, 3*np.pi/2], ['0', '$\pi/2$', '$\pi$', '$3\pi/2$']); ``` ![](https://hackmd.io/_uploads/SkV9DxSH2.png) ### Subplotting Examples <a name="sub"></a> ```python import matplotlib.pyplot as plt fig, ax = plt.subplots(2, 3) fig.subplots_adjust(hspace=0.4, wspace=0.4) for i in range(2): for j in range(3): ax[i, j].text(0.5, 0.5, str((i, j)), fontsize=18, ha='center', va='center') ``` ![](https://hackmd.io/_uploads/SyMpwerSh.png)