Tag Archives: numpy

How to apply gradient color to matplotlib graphs with colormap?

Matplotlib in python offers some useful tools for plotting with gradient colors. Below is a script that plot a sine wave with gradient color based on its y-value. It shows the use of matplotlib.cm.get_cmap to obtain a color map and the use of matplotlib.colors.Normalize to convert a value to the gradient index used for cmap.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import Normalize


X = np.linspace(0, 10, 101)
Y = 10*np.sin(x)

cmap = cm.get_cmap('Blues', len(y))
norm = Normalize(vmin=np.min(Y),vmax=np.max(Y))

for i in range(len(X)-1):
    plt.plot(X[i:i+2], Y[i:i+2], color=cmap(norm(Y[i])))

plt.legend()
plt.grid()
plt.xlabel("x")
plt.ylabel("y")

A more comprehensive list of colormaps can be found in the matplotlib site: https://matplotlib.org/3.3.2/tutorials/colors/colormaps.html

How to conditionally assign value to Pandas dataframes

import pandas as pd

df = pd.DataFrame({'col_1':[0,1,2,3], 'col_2':[0,0,0,0]})
df.loc[df['col_1'] < 2, 'col_2'] = 1
df.loc[df['col_1'] >= 2, 'col_2'] = -1

print(df)

#    col_1  col_2
# 0      0      1
# 1      1      1
# 2      2     -1
# 3      3     -1

The code above creates a dataframe with two columns and assign values to column 2 based on conditional statement on column 1.

How to roll back conda updates

Few days ago I updated my conda packages and I am getting the following errors:

Intel MKL FATAL ERROR: Cannot load mkl_intel_thread.dll.

The ordinal could not be located in the dynamic link library C:\Users\username\Anaconda3\Library\bin\mkl_intel_thread.dll.

(detail of the issue: https://github.com/ContinuumIO/anaconda-issues/issues/10213)

Apparently if the “conda-forge” channel is above the “defaults” channel on the .condarc list (located in home directory), this problem may occur.

 

Then I learnt some useful commands in anaconda:

  • conda list –revisions
  • conda install –revision REVNUM

The first command lists out the revision history of the conda environment, each with a revision number.

The second command will restore your conda environment to the revision you specify.

 

Reference:

https://support.anaconda.com/hc/en-us/articles/360023863914-Restoring-environment-to-a-previous-revision