Can i cycle through line styles in matplotlib
Something like this might do the trick:
import matplotlib.pyplot as plt
from itertools import cycle
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
plt.figure()
for i in range(10):
x = range(i,i+10)
plt.plot(range(10),x,next(linecycler))
plt.show()
Result:
Edit for newer version (v2.22)
import matplotlib.pyplot as plt
from cycler import cycler
#
plt.figure()
for i in range(5):
x = range(i,i+5)
linestyle_cycler = cycler('linestyle',['-','--',':','-.'])
plt.rc('axes', prop_cycle=linestyle_cycler)
plt.plot(range(5),x)
plt.legend(['first','second','third','fourth','fifth'], loc='upper left', fancybox=True, shadow=True)
plt.show()
For more detailed information consult the matplotlib tutorial on "Styling with cycler"
To see the output click "show figure"
How to cycle through both colours and linestyles on a matplotlib figure?
As already mentioned by @datasailor you should multiply both cycles:
cycler_op1 = cycler('color', ['r', 'g', 'b', 'y', 'c', 'k']) \
* cycler('linestyle', ['-', '--', ':', '-.', '-', '--'])
cycler_op2 = cycler('linestyle', ['-', '--', ':', '-.', '-', '--']) \
* cycler('color', ['r', 'g', 'b', 'y', 'c', 'k'])
rc('axes', prop_cycle = cycler_op1 ) # or cycler_op2
Note that multiplication is not commutative and you get different result. Basically, in the first case the color is fixed and the linestyle changes. In the second case the linestyle is fixed and the color changes. In total 6x6 = 36 possibilities.
With such a large number of curves you may experiment with more colors and linestyles.
ls_cycler = cycler('linestyle',
[(0,()), # solid
(0, (1, 10)), # loosely dotted
(0, (1, 5)), # dotted
(0, (1, 1)), # densely dotted
(0, (5, 10)), # loosely dashed
(0, (5, 5)), # dashed
(0, (5, 1)), # densely dashed
(0, (3, 10, 1, 10)), # loosely dashdotted
(0, (3, 5, 1, 5)), # dashdotted
(0, (3, 1, 1, 1)), # densely dashdotted
(0, (3, 10, 1, 10, 1, 10)), # loosely dashdotdotted
(0, (3, 5, 1, 5, 1, 5)), # dashdotdotted
(0, (3, 1, 1, 1, 1, 1))] # densely dashdotdotted
)
color_cycler = cycler('color', [plt.get_cmap('jet')(i/13) for i in range(13)] )
new_cycler = color_cycler + ls_cycler
Result looks like this:
cycling through list of linestyles when plotting columns of a matrix in matplotlib
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))))]
Is there a list of line styles in matplotlib?
According to the doc you could find them by doing this :
from matplotlib import lines
lines.lineStyles.keys()
>>> ['', ' ', 'None', '--', '-.', '-', ':']
You can do the same with markers
EDIT: In the latest versions, there are still the same styles, but you can vary the space between dots/lines.
Set default line style cycler in matplotlib
If you're running matplotlib 1.5 or greater, then you can introduce cyclers for all plot properties in rcParam
using axes.prop_cycle
(and axes.color_cycle
was deprecated in favor of axes.prop_cycle
). In short, you should be able to do something along these lines:
import matplotlib.pyplot as plt
from cycler import cycler
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']) +
cycler('linestyle', ['-', '--', ':', '-.'])))
See this example and the docs for details.
How to pick a new color for each plotted line within a figure in matplotlib?
matplotlib 1.5+
You can use axes.set_prop_cycle
(example).
matplotlib 1.0-1.4
You can use axes.set_color_cycle
(example).
matplotlib 0.x
You can use Axes.set_default_color_cycle
.
Pandas plot line with different line styles?
You can use linestyle
to change each line with different styles.
Here is an example :
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fig,ax = plt.subplots(figsize=(15,5))
ax.set_title('Loss curve', fontsize=15)
ax.set_ylabel('Loss')
ax.set_xlabel('Epoch')
df1 = pd.DataFrame({'epoch' : [10,20,30,40,50,60],
'train_loss' : [6,5,4,3,2,1]})
df2 = pd.DataFrame({'epoch' : [10,20,30,40,50,60],
'train_loss' : [6.5,5.5,4.5,3.5,2.5,1.5]})
df1.plot.line(ax=ax,x='epoch',y=["train_loss"],
linewidth= 1.5, linestyle='-.')
df2.plot.line(ax=ax,x='epoch',y=["train_loss"], linewidth= 1.5,
linestyle='-')
plt.show()
The above code will show the graph as following :
At plt.plot.line(), you can check more styles as solid, dash, dash-dot, dotted, and etc.
python pyplot produce linestyle cycles with different dashes parameters
The tuples are not meant to be strings, they should be python tuples. I.e. use (0, (1, 5))
instead of '(0, (1, 5)))'
.
In general, one way to specify a linestyle is via the linestyle
argument. You may loop over a list,
import matplotlib.pyplot as plt
linestyles = ["--", (0,(5,2,5,5,1,4))]
for i,ls in enumerate(linestyles):
plt.plot([0,1],[i,i], linestyle=ls)
plt.show()
or to create a linestyle cycler,
import matplotlib.pyplot as plt
linestyles = ["--", (0,(5,2,5,5,1,4))]
plt.rcParams["axes.prop_cycle"] += plt.cycler("linestyle", linestyles)
for i in range(2):
plt.plot([0,1],[i,i])
plt.show()
In both cases the resulting plot would look like this
Also refer to the linestyles example.
Related Topics
Prepend a Level to a Pandas Multiindex
JSON.Loads Allows Duplicate Keys in a Dictionary, Overwriting the First Value
Return Multiple Columns from Pandas Apply()
Python/Selenium Incognito/Private Mode
Pygame: Problems with Shooting in Space Invaders
How to Convert an H:Mm:Ss Time String to Seconds in Python
String Similarity Metrics in Python
Pygame Window Not Responding After Few Seconds
Cleanest Way to Hide Every Nth Tick Label in Matplotlib Colorbar
How to Improve My Paw Detection
Python: How to Ignore an Exception and Proceed
Python Create Unix Timestamp Five Minutes in the Future
Extracting Specific Columns in Numpy Array
Asyncio.Gather VS Asyncio.Wait
Replace Negative Values in an Numpy Array
Read Unicode Characters from Command-Line Arguments in Python 2.X on Windows