简体   繁体   中英

Picking plot colors from matplotlib colorbar?

I have a loop that plots data (onto the same plot) every iteration. I'm trying to figure out how to set it so that the color of each data set is drawn from a colorbar depending on the iteration number -- that is, so each iteration of the loop plots a line that is a darker shade of blue (for instance) than the line before it.

My code looks something like this:

for k in numpy.arange(0, iterations, 500):
    h,binEdges=numpy.histogram(data1[k])
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
    plt.plot(bincenters,h,label=(str(k)))
plt.title(title)
plt.legend(fontsize=6)
plt.show()

(data1 is a dictionary.) Does anyone know how this might be done?

The value of a colormap can be obtained by calling the colormap. Colormaps range from 0 to 1. If eg cmap = plt.get_cmap("Blues") , the middle of the colormap is obtained as cmap(0.5) . You may hence call the colormap with the normalized loop index to get a color from it.

import numpy as np
import matplotlib.pyplot as plt

data = [np.random.rand(13+10*i) for i in range(10)]
data1 = dict(zip(range(10),data))

cmap=plt.get_cmap("Blues")
kn = np.arange(10)
for k in kn:
    h,binEdges=np.histogram(data1[k])
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
    plt.plot(bincenters,h,label=(str(k)), color=cmap(float(k)/kn.max()))

plt.legend(fontsize=6)
plt.show()

在此处输入图片说明

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