Home > Enterprise >  plotting using color as a gradient in matplotlib
plotting using color as a gradient in matplotlib

Time:12-08

I am new to visualization in python. I am trying to plot the same dataset on the left but by using colors as gradient and gridlines to make it understandable. But I'm stuck and I don't know what I did, I just used the reference codes I got from other similar questions. Can someone help out?

import random
import matplotlib
import matplotlib.pyplot as plt
import tkinter as tk
from matplotlib.widgets import Slider
from matplotlib import colors
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import style
import numpy as np

style.use('ggplot')
matplotlib.use('TkAgg')

def update(val):
    pos = s_time.val
    ax.axis([pos, pos 10, 20, 40])
    fig.canvas.draw_idle()

def plot():
    canvas = FigureCanvasTkAgg(fig,root)
    canvas.get_tk_widget().pack(side=tk.TOP, fill = tk.BOTH, expand =1)
    
    fig.subplots_adjust(bottom=0.25)

    y_values = [random.randrange(41) for _ in range(40)]
    x_values = [i for i in range(40)]

    ax.axis([0, 9, 20, 40])
    ax.plot(x_values, y_values)

    #cmap = colors.ListedColormap(['red', 'blue','green'])
    #bounds = [0,10,20,30]
    #norm = colors.BoundaryNorm(bounds, cmap.N)
    #ax1.imshow(ax, cmap=cmap, norm=norm)
    im0  = ax1.pcolormesh([x_values,y_values], vmin=0, vmax=1, cmap="RdBu")
    im = fig.colorbar(im0,cax=ax1)
    ax1.grid(which='major', axis='both', linestyle='-', color='white', linewidth=0.5)

    #ax1.set_yticks(np.arange(0, 40, 2.5))

    ax_time = fig.add_axes([0.12, 0.1, 0.78, 0.03])
    return ax_time
    

root = tk.Tk()
fig = plt.Figure(figsize = (10,10),dpi = 150)
ax=fig.add_subplot(121)
ax1=fig.add_subplot(122)
s_time = Slider(plot(), 'Time', 0, 30, valinit=0)
s_time.on_changed(update)
root.mainloop()

CodePudding user response:

Disclaimer: Not sure if I understood the question correctly. Maybe you could provide links to the reference questions.

If you want to add a color gradient to a lineplot in matplotlib, to my knowledge the best bet is to use ax.scatter. A similar question was asked here:
Matplotlib: different color for every point of line plot
To mimic the appearance of a lineplot you need to interpolate your data linearly before passing it to the scatter function. The c keyword argument can be used to assign a color-value to each data point and the cmap argument determines the actual mapping from color-value to color.

Here is a minimally working example:

import matplotlib.pyplot as plt
import numpy as np

f, ax = plt.subplots(1, 1)
y_values = np.random.randint(0, 41, size=40)
x_values = np.arange(0, 40, 1)

x_interp = np.arange(0, 40, 0.01)
y_interp = np.interp(x_interp, x_values, y_values)
ax.grid(alpha=0.5)
artist = ax.scatter(x_interp, y_interp, c=y_interp, cmap='seismic', lw=0)
f.colorbar(artist, ax=ax)

Which yields the following plot

EDIT: After clarification I interpret the question as:
"How do I add a background to a lineplot, that shows a color gradient corresponding to the values on the y-axis".

My suggestion is the following:

import matplotlib.pyplot as plt
import numpy as np
f, a  = plt.subplots(1, 1)

value_range = (vmin, vmax) = (0, 40)
x_range = (xmin, xmax) = (0, 60)

X, Y = np.meshgrid(range(xmin, xmax, 1), range(vmin, vmax, 1))
y_data = np.random.randint(vmin, vmax, size=xmax-xmin)
x_data = np.arange(xmin, xmax, 1)

a.pcolormesh(Y, cmap="seismic", alpha=0.5, edgecolors='gray')
a.plot(x_data, y_data, "k-")

Which then yields the following plot

  • Related