3
votes

I'm very new to python and matplotlib, and I want to create a plot with different colored lines. I know I have to use a colormap, but I'm not sure how. So I have a for loop:

for i in range(len(params)):
    centers,fN = graph.createHistogram(values = NHI[i])
    for j in range(len(centers)): 
        if params[i]!=fidVal:
            vals[j] = (np.log10(origfNHI[j]/fN[j]))/(fidVal-params[i])
        plt.plot(centers,vals)

I want to give each line different colors based on the difference between the value of params[i] and fidVal. If fidVal - params[i] is a negative large number, I want the line to be very red, and if it is a negative small number, I want it to be not as red. Similarly if fidVal - params[i] is positive, I want it to be blue based on that value. Finally, I want the colors to be mapped on a colorbar which would be displayed on the plot.

Alternatively, is there a way I can specify the rgb color of a line when I use plt.plot()? Like, could I say plt.plot(centers,vals,Color(0,0,0))?

What code should I use to solve this problem?

1

1 Answers

3
votes

I will answer about the colormap. You can use the karg color for specify an rgb color with a tuple... It's well explained in the documentation.

"In addition, you can specify colors in many weird and wonderful ways, including full names ('green'), hex strings ('#008000'), RGB or RGBA tuples ((0,1,0,1)) or grayscale intensities as a string ('0.8'). Of these, the string specifications can be used in place of a fmt group, but the tuple forms can be used only as kwargs."

Here you have a very simple example:

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,1,1000)
n=50
for i in range(1,n):
    y = i/float(n)*x**2
    plt.plot(x,y,color=(i/float(n),(i/float(n))**4,(i/float(n))**2))
ax = plt.gca()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
plt.show()

enter image description here