Notebook Articles

Take notes and save or share what you have learned

Articles: 586

How to create a tooltip for a visualization based on d3.js using d3-tip ?

To create a tooltip for a visualization based on d3.js [d3.js](https://d3js.org/) (Data-Driven Documents) a solution is to use [d3-tip](http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js). [image:d3-tip-example size:50 caption:How to create a tooltip for a visualization based on d3.js using d3-tip ?] Script to reproduce the example above: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Example d3-tip with circle</title> </head> <body> <script src=

Comment mettre en couleur une surface délimitée par une ou plusieurs courbes avec matplotlib ?

Quelques exemples de comment mettre en couleur une surface délimitée par une ou plusieurs courbes avec matplotlib en utilisant [Axes.fill_between](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.fill_between.html): [TOC] ### Surface délimitée par une courbe et l'axe des x: [image:how-to-fill-area-matplotlib-01 size:50 caption:Comment mettre en couleur une surface délimitée par une ou plusieurs courbes avec matplotlib ?] import matplotlib.pyplot as plt import numpy as np

How to fill an area in matplotlib ?

Few examples of how to fill an area with matplotlib using [Axes.fill_between](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.fill_between.html): [TOC] ### Fill between a curve and the x axis: [image:how-to-fill-area-matplotlib-01 size:50 caption:How to fill an area in matplotlib ?] import matplotlib.pyplot as plt import numpy as np def f(x): return x**2 x = np.arange(0,10,0.1) y = f(x) plt.plot(x,y,'k--') plt.fill_between(x, y, color='#539ecd') p

How to create and apply a rotation matrix using python ?

To create and apply a rotation matrix using python, a solution is to use numpy: \begin{equation} \left( \begin{array}{cc} \cos(\theta) & -\sin(\theta) \\\\ \sin(\theta) & \cos(\theta) \end{array}\right) . \left( \begin{array}{c} x \\\\ y \end{array}\right) \end{equation} import numpy as np theta = np.radians(30) r = np.array(( (np.cos(theta), -np.sin(theta)), (np.sin(theta), np.cos(theta)) )) print('rotation matrix:') print(r) v = np.array((0,1))

How to calculate and visualize the Kullback-Leibler divergence using python ?

An example of how to calculate and visualize Kullback-Leibler divergence using python: [image:381 size:100 caption:How to calculate and visualize Kullback-Leibler divergence using python ?] #!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab from scipy.stats import norm from scipy.integrate import quad def p(x): return norm.pdf(x, 0, 2) def q(x): return norm.pdf(x, 2, 2) def KL(x

How to use the Newton's method in python ?

In numerical analysis, Newton's method (also known as the Newton–Raphson method), named after Isaac Newton and Joseph Raphson, is a method for finding successively better approximations to the roots (or zeroes) of a real-valued function. [wikipedia](https://en.wikipedia.org/wiki/Newton%27s_method). Example of implementation using python: [image:380 size:50 caption:How to use the Newton's method in python ?] #### Solution 1 from scipy import misc def NewtonsMethod(f, x, tolerance=0.

How to create a Chi-square table using python ?

Example of python code to create a Chi-square table. Note: the code works only with a degree of freedom (df) greater than 2, since the code is based of the Newton method with starting value the approximation x0=df. This approximation does not work for df =1 and 2 (problem of convergence) but work well with df > 2. [image:379 size:50 caption:How to create a Chi-square table using python ?] from scipy import misc from scipy import stats PValueList = [0.995, 0.99, 0.975, 0.95, 0.90, 0

How to calculate a root square in python ?

To calculate a root square in python, there are several options: #### Positive float >>> x = 9.0 >>> x**(0.5) 3.0 with pow() function: >>> pow(x,0.5) 3.0 with math module >>> import math >>> math.sqrt(x) 3.0 with numpy >>> import numpy as np >>> np.sqrt(x) 3.0 #### Complex number >>> z = 1j >>> z 1j with numpy >>> import numpy as np >>> np.sqrt(z) (0.7071067811865476+0.7071067811865

Comment calculer une racine carrée avec python ?

Pour calculer une racine carrée avec python il existe plusieurs possibilités: #### Nombre réel positif >>> x = 9.0 >>> x**(0.5) 3.0 avec la fonction pow(): >>> pow(x,0.5) 3.0 avec le module math >>> import math >>> math.sqrt(x) 3.0 avec numpy >>> import numpy as np >>> np.sqrt(x) 3.0 #### Nombre complexe >>> z = 1j >>> z 1j avec numpy >>> import numpy as np >>> np.sqrt(z) (0.707106

Trouver le coefficient directeur de la droite perpendiculaire à une autre droite

Soit la droite d'équation: \begin{equation} y = a * x + b \end{equation} avec comme coefficient directeur a = -2.5 et d'ordonnée à l'origine b = 5.0 (en bleu sur la figure). L'objectif est de trouver le coefficient directeur $a'$ de la droite perpendiculaire à celle-ci (en orange sur la figure). Pour simplifier les calculs prenons la droite perpendiculaire avec la même ordonnée à l'origine: \begin{equation} y' = a' * x + b \end{equation} [images:perpendicular-line-01;perpendi

How to get the slope of the line perpendicular to another ?

Let's consider the line of equation: \begin{equation} y = a * x + b \end{equation} with the slope a = -2.5 and the intercept b = 5.0 (blue line in the figure). The goal is to find the slope $a'$ of the line perpendicular to it (in orange in the figure). All the perpendicular lines have the same slope $a'$, so to make the calculation more easier let's take the line with the same intercept that the blue line, i.e: \begin{equation} y' = a' * x + b \end{equation} [images:perpendi

How to put the origin in the center of the figure with matplotlib ?

To put the origin in the center of the figure with matplotlib, there is the [spines](https://matplotlib.org/api/spines_api.html#module-matplotlib.spines) module, example: [image:572 size:50 caption:How to put the origin in the center of the figure with matplotlib ?] import numpy as np import matplotlib.pyplot as plt fig = plt.figure() x = np.linspace(-np.pi, np.pi, 100) y = 2*np.sin(x) ax = plt.gca() ax.plot(x, y) ax.grid(True) ax.spines['left'].set_position('zer

How to convert an image to grayscale using python ?

To convert an image to grayscale using python, a solution is to use [PIL](http://www.pythonware.com/products/pil/) example: [images:458;459 dim:1*2 size:100 caption:How to convert an image to grayscale using python ?] from PIL import Image img = Image.open('lena.png').convert('LA') img.save('greyscale.png') Note: the conversion to grayscale is not unique see [l'article de wikipedia's article](http://en.wikipedia.org/wiki/Grayscale)). It is also possible to convert an image to g

How to remove an element from a list in python ?

To remove an element from a list in python, there are several solutions: (1) del [del](https://docs.python.org/release/1.5.1p1/tut/del.html): remove an element for a given index: >>> L1 = ['a','b','c','d','e','f'] >>> del L1[3] >>> L1 ['a', 'b', 'c', 'e', 'f'] >>> del L1[-1] >>> L1 ['a', 'b', 'c', 'e'] for a range of indexes: >>> del L1[1:3] >>> L1 ['a', 'e'] (2) remove (note: remove only the first occurence) >>> l = [

How to check if a point is below or above a straight line using python ?

Example of how to check if a point is below or above a straight line using python ? Let's consider a line of equation y=f(x)=a*x+b, a point P with coordinates (xp,yp) is below the line if: yp - ( a * xp + b ) < 0 or: yp - f(xp) < 0 A point P with coordinates (xp,yp) is above the line if yp - ( a * xp + b ) > 0 or: yp - f(xp) > 0 A point P is on the line if and only if: yp - f(xp) = 0 Example of python code to test if above or below a straigh

How to calculate the slope and the intercept of a straight line with python ?

Calculating with python the slope and the intercept of a straight line from two points (x1,y1) and (x2,y2): x1 = 2.0 y1 = 3.0 x2 = 6.0 y2 = 5.0 a = (y2 - y1) / (x2 - x1) b = y1 - a * x1 print('slope: ', a) print('intercept: ', b) Using a function def slope_intercept(x1,y1,x2,y2): a = (y2 - y1) / (x2 - x1) b = y1 - a * x1 return a,b print(slope_intercept(x1,y1,x2,y2)) Using s simple regression with scipy: from scipy.stats import linregress

Calculer le coefficient directeur et l'ordonnée à l'origine d'une droite avec python ?

Exemple de comment calculer avec python le coefficient directeur et l'ordonnée à l'origine d'une droite connaissant deux points distincts (x1,y1) et (x2,y2): x1 = 2.0 y1 = 3.0 x2 = 6.0 y2 = 5.0 a = (y2 - y1) / (x2 - x1) b = y1 - a * x1 print('slope: ', a) print('intercept: ', b) en définissant une fonction: def slope_intercept(x1,y1,x2,y2): a = (y2 - y1) / (x2 - x1) b = y1 - a * x1 return a,b print(slope_intercept(x1,y1,x2,y2)) En utilisant une r

Intégrer une fonction qui prend plusieurs arguments avec quad de python ?

Avec [quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html) il est possible d'intégrer une fonction qui prend plusieurs arguments, exemple avec une fonction f qui prend deux arguments arg1 et arg2: quad( f, x_min, x_max, args=(arg1,arg2,)) Exemple de code: [image:integrate-function-takes-parameters size:50 caption:Comment intégrer une fonction qui prend plusieurs arguments avec quad de python ?] from scipy.integrate import quad import matplotl

How to integrate a function that takes several parameters using quad in python ?

It is possible to integrate a function that takes several parameters with [quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html) in python, example of syntax for a function f that takes two arguments: arg1 and arg2: quad( f, x_min, x_max, args=(arg1,arg2,)) Example of code using quad with a function that takes multiple arguments: [image:integrate-function-takes-parameters size:50 caption:How to integrate a function that takes several parameters using

How to create a list of tuples with random numbers in python ?

To create a list of tuples with random numbers in python a solution is to use the list comprehensions and random module, example: >>> import random >>> l = [(random.randrange(0, 50), random.randrange(0, 20)) for i in range(10)] >>> l [(22, 17), (7, 19), (2, 12), (37, 14), (7, 17), (34, 9), (16, 17), (25, 10), (3, 2), (38, 5)] to generate random float, a solution is to use [uniform(a,b)](https://docs.python.org/3/library/random.html#random.uniform): >>> l = [(rando

Créer avec python une liste de tuples contenant des nombres aléatoires ?

Avec python pour créer une liste de tuples contenant des nombres aléatoires on peut aussi utiliser les "List comprehensions" avec le module random, example avec des nombres entiers: >>> import random >>> l = [(random.randrange(0, 50), random.randrange(0, 20)) for i in range(10)] >>> l [(22, 17), (7, 19), (2, 12), (37, 14), (7, 17), (34, 9), (16, 17), (25, 10), (3, 2), (38, 5)] on peut aussi générer des nombres décimaux avec [uniform(a,b)](https://docs.python.org/3/librar

How to manually add a legend with a color box on a matplotlib figure ?

To manually add a legend with a color box on a matplotlib figure a solution is to use patches, [exemple](https://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists): [image:proxy-artists size:50 caption:How to manually add a legend with a color box on a matplotlib figure ? ] import matplotlib.patches as mpatches import matplotlib.pyplot as plt red_patch = mpatches.Patch(color='red', label='The red data') plt.legend(handl

Ajouter sur une simple figure une légende avec du texte et une boîte de couleur avec matplotlib

Avec matplotlib on peut facilement ajouter manuellement sur une simple figure une légende avec du texte et une boîte de couleur avec le module patches, [exemple](https://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists): [image:proxy-artists size:50 caption:Ajouter sur une simple figure une légende une boîte de couleur avec matplotlib ] import matplotlib.patches as mpatches import matplotlib.pyplot as plt red_patch = mpa

Use the ROC curve to test the performance of a discrete classifier in python ?

R.O.C analysis (receiver operating characteristic) to test the performance of a discrete classifier in python [TOC] ### Introduction Question: for a given x, does it belong to A population or not ? Let's consider a simple classifier define by a threshold (for example $x_s = 10$), if $x >= x_s$ then $x \in A$ if $x < x_s$ then $x \notin A$ [images:roc-curve-discrete-classifier-01;roc-curve-discrete-classifier-02 dim:1*2 size:100 caption:Use the ROC curve to test the performance of a d

How to plot a simple vertical line on a matplotlib figure ?

To plot a simple vertical line on a matplotlib figure, a solution is to use axvline, example [image:matplotlib-vertical-line size:50 caption:How to plot a simple vertical line on a matplotlib figure ? ] import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2*np.pi, 1000) y1 = np.sin(x) f = plt.figure() ax = f.add_subplot(111) plt.plot(x, y1, '-b', label='sine') plt.axvline(x=np.pi,color='red') plt.title('Matplotlib Vertical Line') plt.xlim(0

About


An article helps to save or share information. After creating an article it is possible to add multiple authors and manage the permissions

Create an article

Search


Use the following form to retrieve an article: