Read Documentation for details: https://matplotlib.org/stable/users/index.html
To begin, let's install the Matplotlib library. We'll use the matplotlib.pyplot
module for basic plots like line & bar charts. It is often imported with the alias plt
.
# To install this library in Jupyter notebook
import sys
!{sys.executable} -m pip install matplotlib --quiet
import matplotlib
matplotlib.__version__ , matplotlib.__path__
('3.5.1', ['/Users/arif/opt/anaconda3/envs/python10/lib/python3.10/site-packages/matplotlib'])
from matplotlib import pyplot as plt
print(dir(plt))
['Annotation', 'Arrow', 'Artist', 'AutoLocator', 'Axes', 'Button', 'Circle', 'Figure', 'FigureCanvasBase', 'FixedFormatter', 'FixedLocator', 'FormatStrFormatter', 'Formatter', 'FuncFormatter', 'GridSpec', 'IndexLocator', 'Line2D', 'LinearLocator', 'Locator', 'LogFormatter', 'LogFormatterExponent', 'LogFormatterMathtext', 'LogLocator', 'MaxNLocator', 'MouseButton', 'MultipleLocator', 'Normalize', 'NullFormatter', 'NullLocator', 'Number', 'PolarAxes', 'Polygon', 'Rectangle', 'ScalarFormatter', 'Slider', 'Subplot', 'SubplotSpec', 'Text', 'TickHelper', 'Widget', '_INSTALL_FIG_OBSERVER', '_IP_REGISTERED', '_IoffContext', '_IonContext', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_api', '_auto_draw_if_interactive', '_backend_mod', '_copy_docstring_and_deprecators', '_get_required_interactive_framework', '_interactive_bk', '_log', '_pylab_helpers', '_setup_pyplot_info_docstrings', '_warn_if_gui_out_of_main_thread', '_xkcd', 'acorr', 'angle_spectrum', 'annotate', 'arrow', 'autoscale', 'autumn', 'axes', 'axhline', 'axhspan', 'axis', 'axline', 'axvline', 'axvspan', 'bar', 'bar_label', 'barbs', 'barh', 'bone', 'box', 'boxplot', 'broken_barh', 'cbook', 'cla', 'clabel', 'clf', 'clim', 'close', 'cm', 'cohere', 'colorbar', 'colormaps', 'connect', 'contour', 'contourf', 'cool', 'copper', 'csd', 'cycler', 'delaxes', 'disconnect', 'docstring', 'draw', 'draw_all', 'draw_if_interactive', 'errorbar', 'eventplot', 'figaspect', 'figimage', 'figlegend', 'fignum_exists', 'figtext', 'figure', 'fill', 'fill_between', 'fill_betweenx', 'findobj', 'flag', 'functools', 'gca', 'gcf', 'gci', 'get', 'get_backend', 'get_cmap', 'get_current_fig_manager', 'get_figlabels', 'get_fignums', 'get_plot_commands', 'get_scale_names', 'getp', 'ginput', 'gray', 'grid', 'hexbin', 'hist', 'hist2d', 'hlines', 'hot', 'hsv', 'importlib', 'imread', 'imsave', 'imshow', 'inferno', 'inspect', 'install_repl_displayhook', 'interactive', 'ioff', 'ion', 'isinteractive', 'jet', 'legend', 'locator_params', 'logging', 'loglog', 'magma', 'magnitude_spectrum', 'margins', 'matplotlib', 'matshow', 'minorticks_off', 'minorticks_on', 'mlab', 'new_figure_manager', 'nipy_spectral', 'np', 'pause', 'pcolor', 'pcolormesh', 'phase_spectrum', 'pie', 'pink', 'plasma', 'plot', 'plot_date', 'plotting', 'polar', 'prism', 'psd', 'quiver', 'quiverkey', 'rc', 'rcParams', 'rcParamsDefault', 'rcParamsOrig', 'rc_context', 'rcdefaults', 'rcsetup', 're', 'register_cmap', 'rgrids', 'savefig', 'sca', 'scatter', 'sci', 'semilogx', 'semilogy', 'set_cmap', 'set_loglevel', 'setp', 'show', 'specgram', 'spring', 'spy', 'stackplot', 'stairs', 'stem', 'step', 'streamplot', 'style', 'subplot', 'subplot2grid', 'subplot_mosaic', 'subplot_tool', 'subplots', 'subplots_adjust', 'summer', 'suptitle', 'switch_backend', 'sys', 'table', 'text', 'thetagrids', 'threading', 'tick_params', 'ticklabel_format', 'tight_layout', 'time', 'title', 'tricontour', 'tricontourf', 'tripcolor', 'triplot', 'twinx', 'twiny', 'uninstall_repl_displayhook', 'violinplot', 'viridis', 'vlines', 'waitforbuttonpress', 'winter', 'xcorr', 'xkcd', 'xlabel', 'xlim', 'xscale', 'xticks', 'ylabel', 'ylim', 'yscale', 'yticks']
import numpy as np
x = np.linspace(-2, 2, 20)
y = x**3
plt.plot(x,y)
plt.show()
# Use plt.subplot() method to add an Axes to the current figure
fig = plt.figure()
ax = plt.subplot()
ax.plot(x,y)
plt.show()
# Use fig.add_subplot() method to add an Axes to the figure on which it is called
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(x,y)
plt.show()
# Use plt.subplots() method to create a figure and a add set of subplots in a single call
fig, ax = plt.subplots()
ax.plot(x,y)
plt.show()
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
fig,ax = plt.subplots()
ax.plot(years, chemical_exports)
plt.show()
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
fig,ax = plt.subplots()
ax.plot(years, chemical_exports)
plt.title("LCI Exports in last 12 years")
plt.show()
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
fig,ax = plt.subplots()
ax.plot(years, chemical_exports)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
plt.title("LCI Exports in last 12 years")
plt.show()
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
fig,ax = plt.subplots()
#fig = plt.figure()
#ax = fig.add_subplot()
ax.plot(years, chemical_exports)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.show()
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(years, chemical_exports)
ax.plot(years, medicine_exports)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.show()
Option1:
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(years, chemical_exports)
ax.plot(years, medicine_exports)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(["Chemicals", "Medicines"])
plt.show()
Limitations of above way of adding a Lagend to your graph:
- This technique expects the sequence of arguments passed to the
plt.legend()
method to be exactly same as the sequence in which the plots are added above using the two calls toax.plot()
method- I mean the sequence of strings/labels that you pass to the
plt.legend()
method will be assigned to the two lines in the exact sequence in which they have been added using the twoax.plot()
methods.- Solution to this problem is use
label
argument toax.plot()
method instead of passing a list of strings to theplt.legend()
method.
Option2:
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(years, chemical_exports, label="Chemicals")
ax.plot(years, medicine_exports, label="Medicines")
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.show()
plt.plot
function supports many arguments for markers:markersize
or ms
: Set the size of markersmarkeredgecolor
or mec
: Set the edge color for markersmarkeredgewidth
or mew
: Set the edge width for markersmarkerfacecolor
or mfc
: Set the fill color for markerschemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(years, chemical_exports, label="Chemicals", marker='o')
ax.plot(years, medicine_exports, label="Medicines", marker='x')
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.show()
plt.plot
function supports many arguments for styling linescolor
or c
: Set the color of the linelinestyle
or ls
: Choose between a solid or dashed linelinewidth
or lw
: Set the width of a lineCheckout the supported colors: https://matplotlib.org/3.1.0/tutorials/colors/colors.html
Check out the documentation for plt.plot
to learn more: [https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot]
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(years, chemical_exports, label="Chemicals", marker='o', c='b', ls='-', lw=2)
ax.plot(years, medicine_exports, label="Medicines", marker='x', c='r', ls=':', lw=2)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.show()
Most of the time we just want to set the marker, line style, and line color. The plt.plot() method can be passed a single string for this purpose fmt='[marker][line][color]
plt.plot(years, sports_export, 'o-g')
This format string cannot be passed as named argument, rather is a positional argument after the x,y arguments to plt.plot() method
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(years, chemical_exports, 'o-g', label="Chemicals")
ax.plot(years, medicine_exports, 'x-r', label="Medicines")
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.show()
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot()
ax.plot(years, chemical_exports, label="Chemicals", marker='o', c='b', ls='-', lw=2)
ax.plot(years, medicine_exports, label="Medicines", marker='x', c='r', ls=':', lw=2)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.grid(True)
plt.show()
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot()
ax.plot(years, chemical_exports, label="Chemicals", marker='o', c='b', ls='-', lw=2)
ax.plot(years, medicine_exports, label="Medicines", marker='x', c='r', ls=':', lw=2)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.annotate("Peak of Chemical Exports", xy=(2016,0.95))
plt.grid(True)
plt.show()
plt.style.available
['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot()
ax.plot(years, chemical_exports, label="Chemicals", marker='o', c='b', ls='-', lw=2)
ax.plot(years, medicine_exports, label="Medicines", marker='x', c='r', ls=':', lw=2)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.annotate("Peak of Chemical Exports", xy=(2016,0.95))
plt.grid(True)
plt.style.use('default')
#plt.style.use('dark_background')
#plt.style.use('fivethirtyeight')
#plt.style.use('ggplot')
plt.show()
xvals
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot()
ax.plot(years,chemical_exports, label="Chemicals", marker='o', c='b', ls='-', lw=2)
ax.plot(years,medicine_exports, label="Medicines", marker='x', c='r', ls=':', lw=2)
ax.set_xlabel("Years")
ax.set_ylabel("Amount (Million US$)")
xvals = np.arange(2011, 2022, 2)
yvals = np.linspace(0.80, 0.98, 10)
ax.set_xticks(xvals)
ax.set_yticks(yvals)
plt.title("LCI Exports in last 12 years")
plt.legend(loc='best')
plt.annotate("Peak of Chemical Exports", xy=(2016,0.95))
plt.grid(True)
plt.style.use('default')
#plt.savefig("mychart.png") # can use .pdf, .ps, .eps, .svg formats
plt.show()
!ls -l mychart.png
fig, ax = plt.subplots(nrows=3, ncols=3)
print(ax)
from matplotlib import pyplot as plt
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
ax1.plot(years, chemical_exports, label='Chemicals', marker='o', c='b', ls='-', lw=2)
ax1.set_title("LCI Chemical exports in last 12 years")
ax1.set_xlabel("Years")
ax1.set_ylabel("Amount (Million Rs.)")
ax2.plot(years, medicine_exports, label='Medicines', marker='x', c='r', ls=':', lw=2)
ax2.set_title("LCI Medicine exports in last 12 years")
ax2.set_xlabel("Years")
ax2.set_ylabel("Amount (Million Rs.)")
plt.tight_layout()
plt.show()
from matplotlib import pyplot as plt
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
ax1.plot(years, chemical_exports, label='Chemicals', marker='o', c='b', ls='-', lw=2)
ax1.set_title("LCI Chemical exports in last 12 years")
ax1.set_xlabel("Years")
ax1.set_ylabel("Amount (Million Rs.)")
ax2.plot(years, medicine_exports, label='Medicines', marker='x', c='r', ls=':', lw=2)
ax2.set_title("LCI Medicine exports in last 12 years")
ax2.set_xlabel("Years")
ax2.set_ylabel("Amount (Million Rs.)")
plt.tight_layout()
plt.show()