Matplotlib: change color code after fact

I draw the course of solving a differential equation (boundary value problem). Each iteration gives a complete set of estimates of the functions f (x), which can then be constructed with respect to x. Each graph is (presumably) closer to the correct solution than the last, until convergence is achieved. A consistent color palette is used to make previous graphs disappear and then saturated.

This works great when the number of iterations is predetermined:

import matplotlib.pyplot as plt ax = plt.subplot(111) cm = plt.get_cmap('OrRd') ax.set_color_cycle([cm(1.*i/(iter+1)) for i in range(1,iter+2)]) ax.plot(x,y) for k in range(iter): # iterative solve ax.plot(x,y) 

However, if I use the convergence criterion instead of a predetermined number of iterations, I will not be able to set_color_cycle in advance. And setting this line after the loop does not work.

I know that I can keep my intermediate results and build a plot only after convergence is achieved, but it seems to me difficult because I really do not need to use all the intermediate results, except to see them on the plot.

So, here are my questions: 1. How to change the color chart of existing graphs after plotting? (This is easy in MATLAB.) 2. How can I do the same with a different set of graphs on the same graph (for example, from a different initial assumption converging to a different solution) without violating the first collection, so that two color maps distinguish collections apart. (This should be obvious with the answer to question 1, but just in case.)

Thank you very much.

+6
source share
3 answers

Use update_colors() to update the colors of all lines:

 import pylab as pl import numpy as np cm = pl.get_cmap('OrRd') x = np.linspace(0, 1, 100) def update_colors(ax): lines = ax.lines colors = cm(np.linspace(0, 1, len(lines))) for line, c in zip(lines, colors): line.set_color(c) fig, ax = pl.subplots() for i in range(10): ax.plot(x, x**(1+i*0.1)) update_colors(ax) 
+3
source

You can also use plt.set_cmap , see here or (more carefully, scroll down) here :

 import numpy as np import matplotlib.pyplot as plt plt.imshow(np.random.random((10,10)), cmap='magma') plt.colorbar() plt.set_cmap('viridis') 
+2
source

One trick that you might consider, instead of trying to change color values ​​after plotting, you can use a black overlay with less than 100% transparency to β€œfade” past plots, for example. an alpha of 10% would dim the brightness of each past graph sequentially.

0
source

Source: https://habr.com/ru/post/958285/


All Articles