Search code examples
matplotlibplotlinestyle

cycling through list of linestyles when plotting columns of a matrix in matplotlib


I am probably missing something obvious. I'm plotting the data contained in the columns of a matrix in a single call using

plot(x,A)

where is x is a 1D numpy arange with a length equal to the number of rows of A. The lineplots this generates are all full lines with a color cycling through the default color cycle set in matplotlib.rc

I know I can modify the color cycle (and can even have a single color and linestyle for all columns). However how can I only cycle the line styles (say through full, dashed, dash-dotted, dotted) and not the color (I want to keep it black) and still keep the simple SINGLE plot call ?

plot(x,A,['k-','k--','k-.','k:']) 

doesn't work.


Solution

  • The related source is in class _process_plot_var_args() in axes.py, as you can see, only the color cycle is defined. A similar linestyle cycle is not possible.

    Therefore we need to do these:

    A=range(10)
    B=np.random.randn(10,12)
    p_list=plt.plot(A, B)
    line_cycle=['-','--','-.',':']
    _=[l.set_linestyle(st) for l, st in zip(p_list, np.repeat(line_cycle, 1+(len(p_list)/len(line_cycle))))]
    

    enter image description here