Visualisering i Python

Introduktion till Python för finans

Adina Howe

Professor

Matplotlib: ett visualiseringspaket

Se fler exempel i Matplotlib-galleriet via den här länken.

matplotlib

Introduktion till Python för finans

matplotlib.pyplot – mångsidiga plottningsfunktioner

import matplotlib.pyplot as plt
Introduktion till Python för finans

matplotlib.pyplot – mångsidiga plottningsfunktioner

  • plt.plot()

    • tar argument som beskriver data som ska plottas
  • plt.show()

    • visar plotten på skärmen
Introduktion till Python för finans

Plottning med pyplot

import matplotlib.pyplot as plt
plt.plot(months, prices)
plt.show()
Introduktion till Python för finans

Plottresultat

Enkel plot 2

Introduktion till Python för finans

Röd heldragen linje

import matplotlib.pyplot as plt
plt.plot(months, prices, color = 'red')
plt.show()
Introduktion till Python för finans

Plottresultat

röd linje

Introduktion till Python för finans

Streckad linje

import matplotlib.pyplot as plt
plt.plot(months, prices, color = 'red', linestyle = '--')
plt.show()
Introduktion till Python för finans

Plottresultat

streck

Introduktion till Python för finans

Färger och linjestilar

color
'green' grön
'red' röd
'cyan' cyan
'blue' blå
linestyle
'-' heldragen linje
'--' streckad linje
'-.' streck-punkt-linje
':' prickad

Mer dokumentation om färger och linjer finns här.

Introduktion till Python för finans

Lägga till etiketter och titlar

import matplotlib.pyplot as plt
plt.plot(months, prices, color = 'red', linestyle = '--')

# Add labels
plt.xlabel('Months')
plt.ylabel('Consumer Price Indexes, $')
plt.title('Average Monthly Consumer Price Indexes')

# Show plot
plt.show()
Introduktion till Python för finans

Plottresultat

etiketterad plot

Introduktion till Python för finans

Lägga till fler linjer

import matplotlib.pyplot as plt
plt.plot(months, prices, color = 'red', linestyle = '--')

# adding an additional line
plt.plot(months, prices_new, color = 'green', linestyle = '--') 

plt.xlabel('Months')
plt.ylabel('Consumer Price Indexes, $')
plt.title('Average Monthly Consumer Price Indexes')
plt.show()
Introduktion till Python för finans

Plottresultat

två linjer

Introduktion till Python för finans

Spridningsdiagram

import matplotlib.pyplot as plt
plt.scatter(x = months, y = prices, color = 'red')
plt.show()
Introduktion till Python för finans

Resultat – spridningsdiagram

spridningsdiagram

Introduktion till Python för finans

Nu kör vi en övning!

Introduktion till Python för finans

Preparing Video For Download...