简体   繁体   中英

matplotlib color gradient between two colors

I want a color gradient between black and red in matplotlib, where the low values are black and become more and more red with increasing Y-value.

import matplotlib.pyplot as plt
xvals = np.arange(0, 1, 0.01)
yvals = xvals
plt.plot(xvals, yvals, "r")
axes = plt.axes()
plt.show()

What do I have to change to get such a color gradient?

From the matplotlib documentation you can check this link as an example.

To create that colormap you just need to do:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

colors = [(0, 0, 0), (1, 0, 0)] # first color is black, last is red
cm = LinearSegmentedColormap.from_list(
        "Custom", colors, N=20)
mat = np.indices((10,10))[1]
plt.imshow(mat, cmap=cm)
plt.show()

This results in this:

自定义颜色图,从黑色到红色

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM