2

I'm plotting several lines within a for block and I set the style of each line using matplotlib's dashes argument.

One (or more) of those lines needs to be continuous. I've found no way to draw such a line other than making a single extremely long dash, as seen in the MCVE below. This works, but feels rather hackish.

Is there a more "correct" way to achieve this?

(I know I can just use plt.plot() with no dashesargument to produce a continuous plot, but I need to produce a lot of custom styled lines, mixed with one or more continuos lines)


MCVE:

import matplotlib.pyplot as plt
import numpy as np


col = ['c', 'm', 'g', 'y', 'k']
c_dash = [[8, 4], [8, 4, 2, 4], [2, 2], [8, 4, 2, 4, 2, 4], [1000, 1]]

for i in range(5):
    x, y = range(10), np.random.uniform(0., 10., 10)
    plt.plot(x, y, color=col[i], dashes=c_dash[i])

plt.savefig('test.png', dpi=300)

enter image description here

3
  • Is all you mean plt.plot(x, y, '-')? Commented May 20, 2016 at 22:34
  • Basically, yes. If you try it, you'll see the dashes argument does not accept '-'. Commented May 20, 2016 at 22:36
  • 1
    Still kind of hacky, but substituting 1000 with np.inf seems to work. Commented May 20, 2016 at 22:39

1 Answer 1

2

If you change your c_dash list to include an offset param ( offset,( on,off sequence ) ) you can then use linestyle as your kwarg instead of dashes. This will allow you to use the linestyle keywords ‘solid’ | ‘dashed’, ‘dashdot’, ‘dotted’ in addition to your custom dashes.

import matplotlib.pyplot as plt
import numpy as np


col = ['c', 'm', 'g', 'y', 'k']
c_dash = [[0,[8, 4]], [0,[8, 4, 2, 4]], 'solid', [0,[8, 4, 2, 4, 2, 4]], 'solid']


for i in range(5):
    x, y = range(10), np.random.uniform(0., 10., 10)
    plt.plot(x, y, color=col[i], linestyle=c_dash[i])

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

That's a nice answer, I wasn't aware of the offset param. Thanks BHawk!

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.