The Open Science Project

Identification


Sign-Up


Create a new notebook

Contributors


Open Science Notebooks

Notes


How to change the color background of a matplotlib figure ?

Daidalos November 20, 2019

Creative Commons License

Examples of how to change the color background of a matplotlib figure: [TOC] ### Using subplot and the option axisbg from pylab import * subplot(111, axisbg='#ababab') t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) plot(t, s) xlabel('x') ylabel('y') title('How to change background color in matplotlib ?') savefig('exemple_01.png') show() [image:376 size:50 caption:How to change the color background of a matplotlib figure ?] source: [How to set opacity of backgroun ...

Elementary operations on lists in python

Daidalos November 20, 2019

Creative Commons License

Examples of elementary operations on lists in python [TOC] ### Create a list Create an empty list >>> l = [] >>> type(myfirstlist) <type 'list'> Create a list with 3 elements >>> l = ['a','b','c'] Note: in a list the elements can have different typrs >>> l = ['hello',1,2] ### Get the number of elements in a list To get the number of elements in a list a solution is to use len() >>> l = ['Pierre', 'Paul', 'Mathieu'] >>> len(l) 3 ...

Hot to sum / add two or several matrices together in python ?

Daidalos November 20, 2019

Creative Commons License

Examples of how to sum / add two or several matrices together in python using numpy: [TOC] ### Add two matrices of same size Let sum two matrices of same size. Let's consider the matrix A: >>> import numpy as np >>> A = np.array(([3,1],[6,4])) >>> A array([[3, 1], [6, 4]]) \begin{equation} A = \left( \begin{array}{ccc} 3 & 1 \\\\ 6 & 4 \end{array}\right) \end{equation} and matrix B: >>> B = np.array(([1,8],[4,2])) >>> B array([[1, 8], [4, 2]] ...

How to get a complex number in polar coordinates in python ?

Daidalos November 16, 2019

Creative Commons License

Examples of how to get a complex number in polar coordinates in python: [TOC] ### Using the python module cmath To get a complex number in polar coordinate a solution is to use the python module [cmath](https://docs.python.org/2/library/cmath.html): >>> import cmath Let's consider the following complex number: >>> z = 2 + 3j to get the polar coordinates: >>> r,theta = cmath.polar(z) >>> r 3.605551275463989 >>> theta 0.982793723247329 Note: to return the c ...

How to create a matrix of complex numbers in python using numpy ?

Daidalos November 15, 2019

Creative Commons License

Examples of how to create a matrix of complex numbers in python using numpy: [TOC] ### Create a matrix of random numbers >>> Z = np.array([[1+2j,1+3j],[5+6j,3+8j]]) >>> Z array([[ 1.+2.j, 1.+3.j], [ 5.+6.j, 3.+8.j]]) ### Create a matrix of random numbers with 0+0j >>> import numpy as np >>> Z = np.zeros(10, dtype=complex) >>> Z array([ 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0. ...

How to get the conjugate of a complex number in python ?

Daidalos November 15, 2019

Creative Commons License

Examples of how to get the conjugate of a complex number z in python: [TOC] ### Get the conjugate of a complex number A solution is to use the python function [conjugate()](http://stackoverflow.com/questions/8370637/complex-numbers-usage-in-python), example >>> z = complex(2,5) >>> z.conjugate() (2-5j) >>> ### Matrix of complex numbers Another example using a matrix of complex numbers import numpy as np >>> Z = np.random.random(10) + np.random. ...

How to extract the real and imaginary parts of a complex number in python ?

Daidalos November 15, 2019

Creative Commons License

To extract the the real and imaginary parts of a complex number z=a+ib in python, a solution is to use z.real and z.imag: [TOC] ### Extract the real and imaginary parts of a complex number >>> z = complex(2,5) >>> z (2+5j) >>> z.real 2.0 >>> z.imag 5.0 ### Matrix of complex number It also works with matrix of complex numbers: >>> import numpy as np >>> Z = np.array([[1+2j,1+3j],[5+6j,3+8j]]) >>> Z array([[ 1.+2.j, 1.+3.j], [ 5.+6. ...

How to get the modulus of complex number in python ?

Daidalos November 15, 2019

Creative Commons License

Examples of how to get the modulus of complex number in python: [TOC] ### Definition The modulus of complex number $z=a+ib$ is: \begin{equation} |z| = |a+ib| = \sqrt{a^2+b^2} \end{equation} with $a$ and $b$ are the real and imaginary parts. ### Create a function to calculate the modulus of complex number To calculate the modulus of complex number a solution is to define a simple python function: >>> import math >>> def complexe_modulo(z): ... a = z.r ...

How to copy a dataframe with pandas in python ?

Daidalos November 14, 2019

Creative Commons License

Example of how to copy a data frame with pandas in python: [TOC] ### Create a dataframe To start let's create a simple dataframe: >>> import pandas as pd >>> import numpy as np >>> data = np.random.randint(100, size=(10,5)) >>> df = pd.DataFrame(data=data,columns=['a','b','c','d','e']) >>> df a b c d e 0 42 94 3 22 28 1 0 85 93 43 18 2 70 10 98 19 26 3 54 72 89 51 61 4 13 44 94 28 34 5 79 4 89 33 81 6 69 37 84 89 ...

How to prepend an n-by-1 column of ones to a matrix in python using numpy ? (machine learning)

Daidalos November 14, 2019

Creative Commons License

Examples of how to prepend an n-by-1 column of ones to a matrix of training input data: [TOC] ### Prepend an n-by-1 column of ones to a training dataset Let's consider the following matrix X of training data X (with n=6 observations and d=3 features): \begin{equation} X = \left( \begin{array}{ccc} x_{11} & x_{12} & x_{13} \\\\ x_{21} & x_{22} & x_{23} \\\\ x_{31} & x_{32} & x_{33} \\\\ x_{41} & x_{42} & x_{43} \\\\ x_{51} & x_{52} & x_{53} \\\\ x_{61} & x_{62} & x_{63} \end ...

How to count the occurrence of an element in a pandas data frame column ?

Daidalos November 08, 2019

Creative Commons License

Examples of how to count the occurrence of an element in a pandas data frame column: [TOC] ### Using value_counts() Lets take for example the file ['default of credit card clients Data Set"](https://archive.ics.uci.edu/ml/datasets/default+of+credit+card+clients#) that can be downloaded [here](https://archive.ics.uci.edu/ml/machine-learning-databases/00350/) >>> import pandas as pd >>> df = pd.read_excel('default of credit card clients.xls', header=1) To get the count of d ...

How to get the shape of a DataFrame in python with pandas ?

Daidalos November 08, 2019

Creative Commons License

Examples of how to get the shape of a DataFrame in python with panda: [TOC] ### Get DataFrame shape Let's consider the following file train.csv (that can be downloaded on kaggle): >>> import pandas as pd >>> df = pd.read_csv('train.csv') To get the shape a solution is to use the function [shape()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.shape.html): >>> print(df.shape) (1460, 81) ### Number of columns Get the number of columns ...

How to read a simple text file in python ?

Daidalos November 08, 2019

Creative Commons License

Example of how to read a simple text file in python: [TOC] ### Read a text file Let's consider the following file [iso_8859-1.txt](https://www.w3.org/TR/PNG/iso_8859-1.txt). To read and close the file do: f = open('iso_8859-1.txt', 'r') f.closed ### Get all the file content To get all the file content a solution is to use f.read(): f = open('iso_8859-1.txt', 'r') data = f.read() f.close and print the content using print(data) returns here: Th ...

How to add some text on a matplotlib figure in python ?

Daidalos November 07, 2019

Creative Commons License

Examples of how to add some text on a matplotlib figure in python: [TOC] ### Add text using pyplot.text() To add some text on a matplotlib figure, a solution is to use the function [matplotlib.pyplot.text()](http://matplotlib.org/api/pyplot_api.html?highlight=figtext) that needs the position of the text (x,y) and the text itself. An example with the text 'Hello World !' at the coordinates (1,35): #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt x ...

How to rename a column name of a DataFrame in pandas ?

Daidalos November 07, 2019

Creative Commons License

Examples of how to rename a column name of a DataFrame in pandas: [TOC] ### Rename a column name using rename() Let's consider the following dataframe >>> import numpy as np >>> import pandas as pd >>> import numpy as np >>> data = np.random.randint(100, size=(5,5)) >>> df = pd.DataFrame(data=data,columns=['c1','c2','c3','c4','c5']) >>> df c1 c2 c3 c4 c5 0 33 93 44 10 38 1 77 27 78 15 84 2 33 50 42 30 63 3 35 54 39 8 21 4 77 11 3 ...

How to remove one or multiple rows in a pandas DataFrame in python ?

Daidalos November 01, 2019

Creative Commons License

Examples of how to remove one or multiple rows in a pandas DataFrame in python [TOC] ### Remove one row Lets create a simple dataframe with pandas >>> data = np.random.randint(100, size=(10,10)) >>> df = pd.DataFrame(data=data) >>> df 0 1 2 3 4 5 6 7 8 9 0 13 44 3 55 13 98 44 87 20 52 1 72 72 96 18 68 84 81 41 8 75 2 53 71 97 27 21 44 61 9 59 87 3 40 94 49 7 56 93 17 62 71 14 4 4 20 56 45 89 78 9 ...

How to remove one or multiple columns in a pandas DataFrame in python ?

Daidalos November 01, 2019

Creative Commons License

Examples of how to remove one or multiple columns in a pandas DataFrame in python: [TOC] ### Remove one column Lets create a simple dataframe >>> import pandas as pd >>> import numpy as np >>> data = np.random.randint(100, size=(10,10)) >>> data array([[55, 38, 97, 91, 22, 12, 87, 55, 38, 91], [44, 39, 64, 45, 33, 26, 28, 9, 86, 40], [10, 98, 55, 3, 99, 41, 25, 8, 36, 47], [84, 82, 55, 73, 29, 28, 85, 99, 7, 92], [84, 38, 45, 75, 9, 45, 89, 19, 6 ...

How to select one or multiple rows in a pandas DataFrame in python ?

Daidalos November 01, 2019

Creative Commons License

Examples of how to select one or multiple rows in a pandas DataFrame in python: [TOC] ### Create a DataFrame Lets consider the following dataset train.csv (that can be downloaded on [kaggle](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data)). To read the file a solution is to use [read_csv()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html): >>> import pandas as pd >>> df = pd.read_csv('train.csv') >>> df.shape (1460, 8 ...

How to replace some elements of a matrix using numpy in python ?

Daidalos October 31, 2019

Creative Commons License

Examples of how to replace some elements of a matrix using numpy in python: [TOC] ### Replace some elements of a 1D matrix Let's try to replace the elements of a matrix called M strictly lower than 5 by the value -1: >>> import numpy as np >>> M = np.arange(10) >>> M array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> M[M > 5 ] = -1 >>> M array([ 0, 1, 2, 3, 4, 5, -1, -1, -1, -1]) ### Replace some elements of a 2D matrix Another exam ...

How to select one or multiple columns in a pandas DataFrame in python ?

Daidalos October 29, 2019

Creative Commons License

Example of how to extract one or several columns of data in a pandas dataframe [TOC] ### Create a dataframe with pandas Let's consider the csv file train.csv (that can be downloaded on [kaggle](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data)). To read the file a solution is to use [read_csv()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html): >>> import pandas as pd >>> df = pd.read_csv('train.csv') >>> df.shape (1460 ...

How to extract one or several columns of data in a pandas dataframe ?

Daidalos October 29, 2019

Creative Commons License

Exemple de comment sélectionner une ou des colonnes de données dans une DataFrame avec pandas ? [TOC] ### Créer une DataFrame avec Pandas Soit par exemple le fichier csv suivant train.csv (que l'on peut télécharger sur [kaggle](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data)). Pour lire le fichier il existe la fonction pandas [read_csv()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html): >>> import pandas as pd >>> df = ...

How to filter missing data (NAN or NULL values) in a pandas DataFrame ?

Daidalos October 28, 2019

Creative Commons License

Examples of how to work with missing data (NAN or NULL values) in a pandas DataFrame: [TOC] ### Create a DataFrame with Pandas Let's consider the csv file train.csv (that can be downloaded on [kaggle](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data)). To read the file a solution is to use [read_csv()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html): >>> import pandas as pd >>> data = pd.read_csv('train.csv') Get DataFr ...

How to add metadata to a data frame with pandas in python ?

Daidalos October 22, 2019

Creative Commons License

Example of how to add metadata to a data frame with pandas in python: [TOC] ### Create a data frame with pandas Example of how to create a simple data frame with pandas import pandas as pd import numpy as np data = np.arange(1,13) data = data.reshape(3,4) columns = ['Home','Car','Sport','Food'] index = ['Alice','Bob','Emma'] df = pd.DataFrame(data=data,index=index,columns=columns) ### Add metadata A solution to add metadata: df.scale = 0.1 df.offset = 1 ...

How to save a large dataset in a hdf5 file using python ? (Quick Guide)

Daidalos October 22, 2019

Creative Commons License

Examples of how to store a large dataset in a hdf5 file using python: [TOC] ### Create arrays of data Let's consider the following matrices of integers (dtype='i'): >>> import numpy as np >>> A = np.random.randint(100, size=(4,4)) >>> A array([[ 1, 99, 79, 46], [69, 4, 29, 60], [56, 94, 16, 16], [52, 13, 37, 86]]) matrix B of dimensions (5,3,3) >>> B = np.random.randint(100, size=(5,3,3)) >>> B array([[[60, 89, 24], [ 4, 98, 48], [19, 39, ...

How to get the names (titles or labels) of a pandas data frame in python ?

Daidalos October 21, 2019

Creative Commons License

Examples of how to get the names (titles or labels) of a pandas data frame in python [TOC] ### Get the row names of a pandas data frame Let's consider a data frame called df. to get the row names a solution is to do: >>> df.index ### Get the row names of a pandas data frame (Exemple 1) Let's create a simple data frame: >>> import pandas as pd >>> import numpy as np >>> data = np.arange(1,13) >>> data = data.reshape(3,4) >>> data array([[ 1, 2, 3, 4], ...

How to read a csv file using pandas in python ?

Daidalos October 20, 2019

Creative Commons License

Example of how to read a csv file using pandas in python: [TOC] ### Read a csv file Let's consider the csv file train.csv (that can be downloaded on [kaggle](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data)). To read the csv file a solution is to use the pandas function [read_csv()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html): >>> import pandas as pd >>> data = pd.read_csv('train.csv') Get array dimensions: >>> ...

How to extract columns names of a pandas dataframe in python ?

Daidalos October 20, 2019

Creative Commons License

With pandas to get the names of a dataframe, there is the attribute columns ([ref](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.columns.html)): >>> DataFrame.columns Examples of applications: [TOC] ### Read a cvs data file and create a dataframe with pandas Let's consider the cvs data file train.csv (that can be downloaded on [kaggle](https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data)) >>> import pandas as pd >>> dat ...

How to get the number of dimensions of a matrix using numpy in python ?

Daidalos October 17, 2019

Creative Commons License

Exemple de comment déterminer le nombre de dimensions d'une matrice en python: [TOC] ### Get the number of dimensions of a matrix Let's consider the following matrix: >>> import numpy as np >>> A = np.array([[3,9,4],[5,8,1],[9,2,5]]) >>> A array([[3, 9, 4], [5, 8, 1], [9, 2, 5]]) To get the shape of the matrix, a solution is to first use [shape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html): >>> A.shape (3, 3) and ...

How to create an identity matrix using numpy in python ?

Daidalos October 17, 2019

Creative Commons License

Examples of how to create an identity matrix using numpy in python ? [TOC] ### Using the numpy function identity Let's create the following identity matrix \begin{equation} I = \left( \begin{array}{ccc} 1 & 0 & 0 \\\\ 0 & 1 & 0 \\\\ 0 & 0 & 1 \end{array}\right) \end{equation} using numpy function identity: >>> import numpy as np >>> I = np.identity(3) >>> I array([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) Another example: \begin{ ...

How to create a data frame in python using pandas ?

Daidalos October 15, 2019

Creative Commons License

Examples of how to create a data frame using the python module pandas [TOC] ### Create a data frame using an array Import pandas and numpy: >>> import pandas as pd >>> import numpy as np Let's consider the following matrix \begin{equation} data = \left( \begin{array}{ccc} 1 & 2 & 3 & 4 \\\\ 5 & 6 & 7 & 8 \\\\ 9 & 10 & 11 & 12 \end{array}\right) \end{equation} >>> data = np.arange(1,13) >>> data = data.reshape(3,4) >>> data array([[ 1, 2, 3, 4], [ 5 ...

How to create and initialize a matrix in python using numpy ?

Daidalos October 11, 2019

Creative Commons License

To create and initialize a matrix in python, there are several solutions, some commons examples using the python module numpy: [TOC] ### Create a simple matrix Create a 1D matrix of 9 elements: \begin{equation} A = \left( \begin{array}{ccc} 1&7& 3& 7& 3& 6& 4& 9& 5 \end{array}\right) \end{equation} >>> import numpy as np >>> A = np.array([1,7,3,7,3,6,4,9,5]) >>> A array([1, 7, 3, 7, 3, 6, 4, 9, 5]) Notice: the shape of the matrix A is here (9,) and not (9,1) >>> ...

How to create a list of uniformly spaced numbers using a logarithmic scale with python ?

Daidalos October 10, 2019

Creative Commons License

Example of how to create a list of uniformly spaced numbers using a logarithmic scale with python: [TOC] ### Using the numpy function logspace Let's create a list of 100 uniformly spaced numbers (between $10^{0.1}$ et $10^{3}$) using a logarithmic scale >>> import numpy as np >>> l = np.logspace(0.1, 3, 100, endpoint=True) >>> l array([ 1.25892541, 1.34676844, 1.44074081, 1.54127022, 1.64881419, 1.76386217, 1.88693776, 2.0 ...

How to find the indexes of the minimum or maximum value(s) in a matrix using python ?

Daidalos October 08, 2019

Creative Commons License

Examples of how to find the indexes of the minimum or maximum value(s) in a matrix using python and the numpy function called [where](https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html): [TOC] Let's consider the following 2D matrix: >>> import numpy as np >>> A = np.random.randint(100, size=(4, 4)) >>> A array([[73, 37, 6, 21], [16, 53, 77, 44], [98, 95, 3, 29], [77, 67, 87, 86]]) ### Find min and max values First, to find the minimum ...

Aqua MODIS Band 6 missing pixels restoration using Gaussian processes

Ben October 08, 2019

Creative Commons License

Ongoing research ... Goal: To develop an algorithm (in python) based on Gaussian processes to restore the Aqua MODIS Band 6 missing pixels: [images:modis-band6-missing-data-restoration-01;modis-band6-missing-data-restoration-11 dim:1*2 size:80 caption:Aqua MODIS Band 6 missing pixels restoration using Gaussian processes] [TOC] ### Get and plot the data #!/usr/bin/env python from pyhdf.SD import SD, SDC from pylab import figure, cm import numpy as np import matplotlib ...

How to delete rows with values ​​below and above a minimum and maximum value in a pandas data frame ?

Daidalos October 05, 2019

Creative Commons License

A solution to delete rows with values ​​below and above a minimum and maximum value in a pandas data frame is to use the function [between()](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html). Let's consider the following data frame >>> import pandas as pd >>> data = {'Label':['a','b','c','d','e','f','g','h','i','j'],'Value 1':[0,9,3,7,2,6,5,9,6,3], 'Value 2':[56,34,99,11,78,89,34,94,65,36]} >>> df = pd.DataFrame(data) >>> df Label Value 1 V ...

How to convert a pdf document pages to images using python ?

Daidalos October 01, 2019

Creative Commons License

Examples of how to convert a pdf document pages to images using python [TOC] ## 1. Using the python module pdf2image The python module pdf2image is available on [github](https://github.com/Belval/pdf2image). To install it a solution is to use pip: pip install pdf2image Note: the module needs poppler to run. If you use anaconda python distrubtion, it can be installed for example using the following command: conda install -c conda-forge poppler Then the module can now ...

How to create a matrix of random integers in python ?

Daidalos October 01, 2019

Creative Commons License

To create a matrix of random integers in python, a solution is to use the numpy function [randint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.randint.html), examples: [TOC] ### 1D matrix with random integers between 0 and 9: Example of 1D matrix with 20 random integers between 0 and 9: >>> import numpy as np >>> A = np.random.randint(10, size=(20)) >>> A array([1, 8, 4, 3, 5, 7, 1, 2, 9, 6, 7, 6, 3, 1, 4, 6, 4, 9, 9, 6]) returns for example: ...

How to use Gaussian processes in machine learning to do a regression or classification using python 3 ?

Daidalos August 08, 2019

Creative Commons License

Examples of how to use Gaussian processes in machine learning to do a regression or classification using python 3: [TOC] ### A 1D example: from numpy.linalg import inv import matplotlib.pyplot as plt import numpy as np X = np.array([1., 3., 5., 6., 7., 8.]) Y = X * np.sin(X) X = X[:,np.newaxis] sigma_n = 1.5 plt.grid(True,linestyle='--') plt.errorbar(X, Y, yerr=sigma_n, fmt='o') plt.title('Gaussian Processes for regression (1D Case) Training Data', f ...

How to add a number to a matrix diagonal elements in python ?

Daidalos August 06, 2019

Creative Commons License

Example of how to add a number to a matrix diagonal elements in python ? [TOC] ### Replace the diagonal element by a same number To replace the diagonal element by a same number, a solution is to use the numpy function [numpy.fill_diagonal](https://docs.scipy.org/doc/numpy/reference/generated/numpy.fill_diagonal.html) >>> import numpy as np >>> A = np.arange(9).reshape(3,3) >>> A array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.fill_diagonal(A, 100) >>> A arra ...

How to perform mathematical operations on array elements in python ?

Daidalos August 02, 2019

Creative Commons License

Examples of how to perform mathematical operations on array elements ("element-wise operations") in python: [TOC] ### Add a number to all the elements of an array Let's consider the following array: \begin{equation} A = \left( \begin{array}{ccc} 0 & 1 & 2 \\\\ 3 & 4 & 5 \\\\ 6 & 7 & 8 \end{array}\right) \end{equation} >>> import numpy as np >>> A = np.arange(9).reshape(3,3) >>> A array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) to add a constant number, a s ...

How to add / sum the elements of an array in python ?

Daidalos July 31, 2019

Creative Commons License

To sum the elements of an array in python, a solution is to use the numpy function [sum](http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html), example: [TOC] ### Sum all elements >>> import numpy as np >>> M = np.array([[1, 2], [3, 4]]) >>> M array([[1, 2], [3, 4]]) >>> np.sum(M) 10 Can be used with real numbers as well: >>> M = np.array([[1.0, 2.0], [3.1, 4.4]]) >>> np.sum(M) 10.5 ### Sum elements ov ...

How to change the size of axis labels in matplotlib ?

Daidalos July 31, 2019

Creative Commons License

Examples of how to change the size of axis labels in matplotlib: [TOC] ### Change the size of x-axis labels A solution to change the size of x-axis labels is to use the pyplot function [xticks](https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks): matplotlib.pyplot.xticks(fontsize=14) example: #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import math pi = math.pi x_list = np.arange(-2*pi,2*pi,0.1) y_list = [math. ...

How to calculate a root mean square using python ?

Daidalos July 31, 2019

Creative Commons License

An example of how to calculate a root mean square using python in the case of a linear regression model: \begin{equation} y = \theta_1 x + \theta_0 \end{equation} [TOC] ### Plot the data Let's generate an ensemble of data with: \begin{equation} y = 3x + 2 \end{equation} import matplotlib.pyplot as plt import numpy as np X = 4 * np.random.rand(1000,1) X_b = np.c_[np.ones((1000,1)), X] Y = 2 + 3 * X + np.random.randn(1000,1) plt.plot(X,Y,'.') plt.x ...

How to plot a dashed line in matplotlib ?

Daidalos July 25, 2019

Creative Commons License

Examples of how to plot dashed lines in matplotlib: [TOC] ### Plot a dashed line To plot a dashed line a solution is to add '--'' ':' or '-:', example: import matplotlib.pyplot as plt x = [1,10] y = [3,6] plt.plot(x,y,'--') plt.savefig('DashedLine_01.png') plt.show() [image:524 size:50 caption:How to plot a dashed line in matplotlib using '--'] import matplotlib.pyplot as plt x = [1,10] y = [3,6] plt.plot(x,y,':') plt.savefig('DashedLine_02.p ...

How to put axis in polar coordinates in matplotlib ?

Daidalos July 25, 2019

Creative Commons License

Examples of how to put axis in polar coordinates in matplotlib: [TOC] ### Axis in polar coordinates To put the axis in polar coordinates in matplotlib, a solution is to use the option projection='polar', example: [image:polar-coordinates-01 size:50 caption:How to put axis in polar coordinates in matplotlib ?] import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='polar') plt.savefig("polar_coordinates_01.png", bbox_inches='tight') ...

How to plot MODIS cloud re and tau LUT (Nakajima and King's diagram) using python ?

Ben June 27, 2019

Creative Commons License

An example of how to plot MODIS cloud re and tau LUT (Nakajima and King's plot) in python using matplotlib: [TOC] ### How to get and read the Data Note: the LUTs are available [here](https://modis-atmosphere.gsfc.nasa.gov/products/cloud/luts) from pyhdf.SD import SD, SDC from scipy import interpolate import matplotlib.pyplot as plt import numpy as np import math import matplotlib.patches as mpatches import matplotlib.cm as cm file = SD('./MODIS_C6_LUTS/examples/oc ...

How to write a simple python code to find the intersection point between two straight lines ?

Daidalos June 21, 2019

Creative Commons License

Example of how to write a simple python code to find the intersection point between two straight lines: [TOC] ### Plot the lines import matplotlib.pyplot as plt import numpy as np m1, b1 = 1.0, 2.0 # slope & intercept (line 1) m2, b2 = 4.0, -3.0 # slope & intercept (line 2) x = np.linspace(-10,10,500) plt.plot(x,x*m1+b1) plt.plot(x,x*m2+b2) plt.xlim(-2,8) plt.ylim(-2,8) plt.title('How to find the intersection of two straight lines ?', fontsize=8) plt.gr ...

How to plot horizontal lines with matplotlib ?

Daidalos June 21, 2019

Creative Commons License

Examples of how to plot horizontal lines with matplotlib: [TOC] ### Plot horizontal lines To plot horizontal lines, a solution is to use axhline, example [image:matplotlib-horizontal-line-01 size:50 caption:How to plot horizontal lines with matplotlib ?] 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) plt.axhline(y=0.5) plt.axhline(y=-0.5) plt ...

How to plot an angle in python using matplotlib ?

Daidalos June 18, 2019

Creative Commons License

An example step by step of how to plot an angle in python using matplotlib and basic mathematics: [TOC] ### Define two lines [image:plot-an-angle-matplotlib-01 size:50 caption:How to plot an angle in python using matplotlib ?] import matplotlib.pyplot as plt import numpy as np m1, b1 = 0.1, 2.0 # slope & intercept (line 1) m2, b2 = 2.0, -3.0 # slope & intercept (line 2) x = np.linspace(-10,10,500) plt.plot(x,x*m1+b1) plt.plot(x,x*m2+b2) plt.xlim(-2,8) plt.yl ...

How to plot a circle in python using matplotlib ?

Daidalos June 18, 2019

Creative Commons License

Examples of how to plot a circle in python using matplotlib: [TOC] ### Plot a circle using plot() To plot a circle a first solution is to use the function plot(): [image:plot-circle-matplotlib-01 size:50 caption:How to plot a circle in python using matplotlib ?] import numpy as np import matplotlib.pyplot as plt theta = np.linspace(0, 2*np.pi, 100) r = np.sqrt(1.0) x1 = r*np.cos(theta) x2 = r*np.sin(theta) fig, ax = plt.subplots(1) ax.plot(x1, x2) ax.se ...

Search