2

I have successfully displayed my numpy data to matplotlib with gradient colors, but in the matplotlib the color gradient appears horizontally, how to make the gradient visible vertically?

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
c = np.arange(1,200)
x = np.arange(1,200)
y = np.random.randint(low=1, high=100, size=200)

cm = plt.get_cmap('jet')

fig = plt.figure(figsize=(10,5))
ax1 = plt.subplot(111)

no_points = len(c)
ax1.set_color_cycle([cm(1.*i/(no_points-1)) for i in range(no_points-1)])

for i in range(no_points-1):
    bar = ax1.plot(x[i:i+2],y[i:i+2])
plt.show()

The result is the following:

result

Instead, I'd like to have a vertical color gradient.

1

1 Answer 1

2

I changed your code a tiny bit, but mainly just merged it with the matplotlib recipe that the commenter referred to. This works for me:

import numpy as np
import matplotlib.pyplot as plt

x_ = np.linspace(1, 200, 200)
y_ = np.random.randint(low=1, high=100, size=200)

# You need to interpolate because your line segments are short.
x = np.linspace(1, 200, 4000)
y = np.interp(x, x_, y_)

# Now follow the maplotlib recipe.
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

fig, ax = plt.subplots(figsize=(15, 5))

norm = plt.Normalize(y.min(), y.max())
lc = LineCollection(segments, cmap='viridis', norm=norm)

lc.set_array(y)
lc.set_linewidth(2)
line = ax.add_collection(lc)
plt.colorbar(line, ax=ax)

ax.set_xlim(x.min(), x.max())
ax.set_ylim(-10, 110)

plt.show()

Result:

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.