2

I don't really understand the documentation on colorbar I wanted explanation on a basic example. So below I am plotting exp(-x*a) for a={1, 2, 3, 4}. How do I add color bar with the values of a.

import numpy as np
import matplotlib.pyplot as plt

def func(x,a):
    return np.exp(-x*a)
x = np.linspace(0, 5)

for a in range(1,5):
    plt.plot(func(x,a))
plt.show()

I'm confused with imshow, subplot, ax.

3
  • imshow does something completely different. subplots allows you to you guessed it create subplots. You can access the ax within the loop and do whatever you want to do. Commented Aug 27, 2022 at 10:34
  • 3
    you need a colorbar if you want to color-code value in the third dimension, plot shows a line plot - so the value is on the second dimension (y-axis), no need for a colorbar Commented Aug 27, 2022 at 10:51
  • It sounds like you really want a legend. Maybe start with a tutorial or two: matplotlib.org/stable/plot_types/index Commented Aug 27, 2022 at 20:03

1 Answer 1

8

Colour schemes are defined in the range 0 to 1, therefore you first need to normalise your values (0 to 5) to the range 0 to 1. Then you can pull the colour from the colormap. At the end you have to plot a color bar using the colour map and norm that you chose on the axis you used for plotting.

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


def func(x, a):
    return np.exp(-x * a)


x = np.linspace(0, 5)

fig, ax = plt.subplots()

# define color map
cmap = cm.get_cmap("Spectral")

# need to normalize because color maps are defined in [0, 1]
norm = colors.Normalize(0, 5)

for a in range(1, 5):
    ax.plot(x, func(x, a), 
        color=cmap(norm(a)))  # get color from color map 

# plot colorbar
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

plt.show()

The plot looks like this:enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.