Python: Matplotlib

Utilizzo l’environment conda py3

1
~$ conda activate py3

Versione modulo installato

1
2
3
4
5
6
7
8
9
10
11
~$ pip show matplotlib
Name: matplotlib
Version: 3.2.2
Summary: Python plotting package
Home-page: https://matplotlib.org
Author: John D. Hunter, Michael Droettboom
Author-email: matplotlib-users@python.org
License: PSF
Location: /home/user/miniconda3/envs/py3/lib/python3.7/site-packages
Requires: pyparsing, numpy, cycler, kiwisolver, python-dateutil
Required-by: seaborn

Matplotlib

Documentazione Matplotlib
Documentazione Matplotlib rougier

1
2
import matplotlib.pyplot as plt
import numpy as np
1
2
3
4
# per plottare sul notebook
%matplotlib inline
# per plottare senza notebook
# plt.show()
1
2
x = np.linspace(0,5,11)
y = x**2

Functional method

1
2
3
4
5
plt.plot(x,y, 'r-') # r- red
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Title')
# plt.show() # non è necessario se si è specificato %matplotlib inline
1
Text(0.5, 1.0, 'Title')

png

1
2
3
4
5
6
# multiple plot same canvas
plt.subplot(1,2,1)
plt.plot(x,y,'r-')

plt.subplot(1,2,2) # 1 row, by 2 columns, 2nd plot
plt.plot(y,x,'b')
1
[<matplotlib.lines.Line2D at 0x7f4e6c5409d0>]

png

Object Oriented method

1
2
3
4
5
6
7
8
fig = plt.figure()

axes = fig.add_axes([0.1,0.1,0.8,0.8]) # left axsis, bottom, width, height

axes.plot(x,y)
axes.set_xlabel('X Label')
axes.set_ylabel('Y Label')
axes.set_title('Title')
1
Text(0.5, 1.0, 'Title')

png

1
2
3
4
5
6
7
8
9
10
11
# multi plot
fig = plt.figure()

axes1 = fig.add_axes([0.1,0.1,0.8,0.8])
axes2 = fig.add_axes([0.2,0.5,0.4,0.3])

axes1.plot(x,y)
axes1.set_title('Larger Plot')

axes2.plot(y,x)
axes2.set_title('Smaller Plot')
1
Text(0.5, 1.0, 'Smaller Plot')

png

subplots

1
2
3
4
fig,axes = plt.subplots(nrows=1,ncols=2)
# axes è un array (list) di due oggetti matplotlib, che potrei iterare
for current_ax in axes:
    current_ax.plot(x,y)

png

1
2
3
4
5
6
7
8
9
10
# quindi si può lavorare anche sugli index
fig,axes = plt.subplots(nrows=1,ncols=2)

axes[0].plot(x,y)
axes[0].set_title('First Plot')

axes[1].plot(x,y)
axes[1].set_title('Second Plot')

plt.tight_layout() # pulisce le eventuali sovrapposizioni

png

Figure Size and DPI

1
2
3
4
fig = plt.figure(figsize=(8,2),dpi=100) # 8 inches

ax = fig.add_axes([0,0,1,1])
ax.plot(x,y)
1
[<matplotlib.lines.Line2D at 0x7f4e60dc8750>]

png

1
2
3
4
5
6
fig,axes = plt.subplots(nrows=2,ncols=1,figsize=(8,2),dpi=100) # 8 inches

axes[0].plot(x,y)
axes[1].plot(y,x)

plt.tight_layout()

png

1
pwd
1
'/media/user/Public/Python/Course 001'
1
2
# salvare plot, png, jpg, svg
fig.savefig('my_picture.png',dpi=200)
1
2
3
4
5
6
7
8
9
10
11
# legends
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.plot(x,x**2,label='X Squared')
ax.plot(x,x**3,label='X Cubed')

# per il parametro loc vedi la guida
# https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
ax.legend(loc=(0.1,0.1)) # una tupla che specifica la posizione
1
<matplotlib.legend.Legend at 0x7f4e5bae5950>

png

1
2
3
4
5
6
# colors, line width, trasparenza
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.plot(x,y,color='purple',lw=2,alpha=0.5,ls='-.',marker='o',markersize=20,markerfacecolor='red',markeredgewidth=5,markeredgecolor='black') # Color #FF8C00, etc RGB Hex Code; lwd o linewidth; ls o linestyle step, --, :, etc.
1
[<matplotlib.lines.Line2D at 0x7fa306796610>]

png

1
2
3
4
5
6
7
8
9
# plot range
fig = plt.figure()

ax = fig.add_axes([0,0,1,1])

ax.plot(x,y,color='purple',lw=2,ls='--')

ax.set_xlim([0,1])
ax.set_ylim([0,2])
1
(0.0, 2.0)

png

Special Plot Types

1
plt.scatter(x,y)
1
<matplotlib.collections.PathCollection at 0x7fa305280190>

png

1
# scatterplot, histogram, boxplot

Altro

1
2
3
x = np.arange(0,100)
y = x*2
z = x**2
1
2
3
4
fig = plt.figure()

axes1 = fig.add_axes([0,0,1,1])
axes2 = fig.add_axes([0.2,0.5,0.2,0.2])

png

1
2
3
4
5
6
7
8
9
10
11
12
13
axes1.plot(x,z,color='red', ls='-.', lw=3)
axes1.set_xlabel('x')
axes1.set_ylabel('y')
axes1.set_title('full')

axes2.plot(x,y,color='blue')
axes2.set_xlabel('x')
axes2.set_ylabel('y')
axes2.set_title('zoom')
axes2.set_xlim([20,22])
axes2.set_ylim([30,50])

fig # si può anche richiamare alla fine invece di reinizializzare la fig all'inizio della cella

png

Matplotlib with Pandas

1
2
3
4
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
1
pwd
1
'/media/user/Public/Python/Course 001'
1
2
df1 = pd.read_csv('df1',index_col=0)
df1.head()
A B C D
2000-01-01 1.339091 -0.163643 -0.646443 1.041233
2000-01-02 -0.774984 0.137034 -0.882716 -2.253382
2000-01-03 -0.921037 -0.482943 -0.417100 0.478638
2000-01-04 -1.738808 -0.072973 0.056517 0.015085
2000-01-05 -0.905980 1.778576 0.381918 0.291436
1
2
df2 = pd.read_csv('df2')
df2.head()
a b c d
0 0.039762 0.218517 0.103423 0.957904
1 0.937288 0.041567 0.899125 0.977680
2 0.780504 0.008948 0.557808 0.797510
3 0.672717 0.247870 0.264071 0.444358
4 0.053829 0.520124 0.552264 0.190008
1
2
# histogram
df1['A'].hist(bins=30)
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdb58a2b10>

png

1
2
3
# ggplot style
plt.style.use('ggplot')
df1['A'].plot(kind='hist',bins=30)
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdb0856a10>

png

1
2
plt.style.use('fivethirtyeight')
df1['A'].hist(bins=30)
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdb032ced0>

png

1
2
plt.style.use('dark_background')
df1['A'].plot.hist(bins=30)
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdabfaa710>

png

1
2
3
# area plot
plt.style.use('bmh')
df2.plot.area(alpha=0.4)
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdabb399d0>

png

1
2
# bar plot
df2.plot.bar(stacked=True) # gli index come variabili categoriche
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdabab23d0>

png

1
df1.index
1
2
3
4
5
6
Index(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05',
       '2000-01-06', '2000-01-07', '2000-01-08', '2000-01-09', '2000-01-10',
       ...
       '2002-09-17', '2002-09-18', '2002-09-19', '2002-09-20', '2002-09-21',
       '2002-09-22', '2002-09-23', '2002-09-24', '2002-09-25', '2002-09-26'],
      dtype='object', length=1000)
1
2
# line plot
df1.plot.line(y="B",figsize=(12,3),lw=1) # di default prende l'index per le ascisse
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdab89d2d0>

png

1
2
# scatterplot
df1.plot.scatter(x='A',y='B',c='C',cmap='coolwarm')
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdab6d9a50>

png

1
2
# scatterplot bubble
df1.plot.scatter(x='A',y='B',s=df1['C']*10)
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdab4c3790>

png

1
2
3
# boxplot
# df2.boxplot()
df2.plot.box() # si può anche specificare by per il gruppo
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdaab90510>

png

1
2
3
# hexagonal plot
df = pd.DataFrame(np.random.randn(1000,2),columns=['a','b'])
df.head()
a b
0 0.391031 1.272535
1 -0.084391 0.471284
2 3.207212 -0.404945
3 1.951644 -0.234280
4 2.843900 0.860997
1
df.plot.hexbin(x='a',y='b',gridsize=25,cmap='magma')
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdab11a150>

png

1
2
# kernel density estimation
df2['a'].plot.kde()
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdab06edd0>

png

1
2
# density
df2.plot.density()
1
<matplotlib.axes._subplots.AxesSubplot at 0x7efdab17a1d0>

png

Altro

1
2
3
4
# legenda esterna
fig = plt.figure()
df2.plot.density(ax=fig.gca())
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
1
<matplotlib.legend.Legend at 0x7efdaabaa710>

png

Tags:

Updated: