How to draw vertical lines on a given plot in matplotlib?
Given a plot of signal in time representation, how to draw lines marking corresponding time index?
Specifically, given a signal plot with time index ranging from 0 to 2.6(s), I want to draw vertical red lines indicating corresponding time index for the list [0.22058956, 0.33088437, 2.20589566]
, how can I do it?
python matplotlib
add a comment |
Given a plot of signal in time representation, how to draw lines marking corresponding time index?
Specifically, given a signal plot with time index ranging from 0 to 2.6(s), I want to draw vertical red lines indicating corresponding time index for the list [0.22058956, 0.33088437, 2.20589566]
, how can I do it?
python matplotlib
add a comment |
Given a plot of signal in time representation, how to draw lines marking corresponding time index?
Specifically, given a signal plot with time index ranging from 0 to 2.6(s), I want to draw vertical red lines indicating corresponding time index for the list [0.22058956, 0.33088437, 2.20589566]
, how can I do it?
python matplotlib
Given a plot of signal in time representation, how to draw lines marking corresponding time index?
Specifically, given a signal plot with time index ranging from 0 to 2.6(s), I want to draw vertical red lines indicating corresponding time index for the list [0.22058956, 0.33088437, 2.20589566]
, how can I do it?
python matplotlib
python matplotlib
edited Jul 28 '14 at 18:44
Gabriel
4,74111322
4,74111322
asked Jul 28 '14 at 4:29
Francis
1,4333924
1,4333924
add a comment |
add a comment |
5 Answers
5
active
oldest
votes
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
6
But how do I plot the line on a given axis object?
– Eric
Jun 27 '16 at 17:55
4
@Eric ifax
is the object, thenax.axvline(x=0.220589956)
seems to work for me.
– Joel
Jan 17 at 0:10
The arguments for axvline are scalar from 0 to 1, relative to the plot window. How do you draw a line at a given x or y position, such as 2.205... that was asked in this question?
– Edward Ned Harvey
Jul 29 at 15:25
Looks like stackoverflow.com/questions/16930328/… has an answer.plt.plot((x1,x2),(y1,y2))
– Edward Ned Harvey
Jul 29 at 15:30
1
Please note, ymax and ymin should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. If you are using values beyond this range, you will need to translate the y positions with the correct ratio.
– Dylan Kapp
Nov 3 at 19:21
add a comment |
For multiple lines
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
how do we put a legend to the vertical line?
– Charlie Parker
Oct 17 '17 at 20:09
@CharlieParker consider asking a separate question. This part of matplotlib documentation may help you
– Ciprian Tomoiagă
Oct 19 '17 at 13:15
@CharlieParker An extra optionlabel='label'
does the work but you need to callplt.legend([options])
later
– kon psych
Dec 6 '17 at 3:31
add a comment |
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
- Each line is a separate plot object, which causes things to be very slow when you have many lines.
- When you create the legend each line has a new entry, which may not be what you want.
Instead you can use the following convenience functions which create all the lines as a single plot object:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
Good points. What aboutplt.vlines(xs,*plt.ylim())
?
– Vincenzooo
Mar 25 at 21:45
add a comment |
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
import matplotlib.pyplot as plt
xcoords = [0.1, 0.3, 0.5]
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
add a comment |
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24988448%2fhow-to-draw-vertical-lines-on-a-given-plot-in-matplotlib%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
6
But how do I plot the line on a given axis object?
– Eric
Jun 27 '16 at 17:55
4
@Eric ifax
is the object, thenax.axvline(x=0.220589956)
seems to work for me.
– Joel
Jan 17 at 0:10
The arguments for axvline are scalar from 0 to 1, relative to the plot window. How do you draw a line at a given x or y position, such as 2.205... that was asked in this question?
– Edward Ned Harvey
Jul 29 at 15:25
Looks like stackoverflow.com/questions/16930328/… has an answer.plt.plot((x1,x2),(y1,y2))
– Edward Ned Harvey
Jul 29 at 15:30
1
Please note, ymax and ymin should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. If you are using values beyond this range, you will need to translate the y positions with the correct ratio.
– Dylan Kapp
Nov 3 at 19:21
add a comment |
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
6
But how do I plot the line on a given axis object?
– Eric
Jun 27 '16 at 17:55
4
@Eric ifax
is the object, thenax.axvline(x=0.220589956)
seems to work for me.
– Joel
Jan 17 at 0:10
The arguments for axvline are scalar from 0 to 1, relative to the plot window. How do you draw a line at a given x or y position, such as 2.205... that was asked in this question?
– Edward Ned Harvey
Jul 29 at 15:25
Looks like stackoverflow.com/questions/16930328/… has an answer.plt.plot((x1,x2),(y1,y2))
– Edward Ned Harvey
Jul 29 at 15:30
1
Please note, ymax and ymin should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. If you are using values beyond this range, you will need to translate the y positions with the correct ratio.
– Dylan Kapp
Nov 3 at 19:21
add a comment |
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
edited Jul 28 '14 at 4:46
answered Jul 28 '14 at 4:34
Gabriel
4,74111322
4,74111322
6
But how do I plot the line on a given axis object?
– Eric
Jun 27 '16 at 17:55
4
@Eric ifax
is the object, thenax.axvline(x=0.220589956)
seems to work for me.
– Joel
Jan 17 at 0:10
The arguments for axvline are scalar from 0 to 1, relative to the plot window. How do you draw a line at a given x or y position, such as 2.205... that was asked in this question?
– Edward Ned Harvey
Jul 29 at 15:25
Looks like stackoverflow.com/questions/16930328/… has an answer.plt.plot((x1,x2),(y1,y2))
– Edward Ned Harvey
Jul 29 at 15:30
1
Please note, ymax and ymin should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. If you are using values beyond this range, you will need to translate the y positions with the correct ratio.
– Dylan Kapp
Nov 3 at 19:21
add a comment |
6
But how do I plot the line on a given axis object?
– Eric
Jun 27 '16 at 17:55
4
@Eric ifax
is the object, thenax.axvline(x=0.220589956)
seems to work for me.
– Joel
Jan 17 at 0:10
The arguments for axvline are scalar from 0 to 1, relative to the plot window. How do you draw a line at a given x or y position, such as 2.205... that was asked in this question?
– Edward Ned Harvey
Jul 29 at 15:25
Looks like stackoverflow.com/questions/16930328/… has an answer.plt.plot((x1,x2),(y1,y2))
– Edward Ned Harvey
Jul 29 at 15:30
1
Please note, ymax and ymin should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. If you are using values beyond this range, you will need to translate the y positions with the correct ratio.
– Dylan Kapp
Nov 3 at 19:21
6
6
But how do I plot the line on a given axis object?
– Eric
Jun 27 '16 at 17:55
But how do I plot the line on a given axis object?
– Eric
Jun 27 '16 at 17:55
4
4
@Eric if
ax
is the object, then ax.axvline(x=0.220589956)
seems to work for me.– Joel
Jan 17 at 0:10
@Eric if
ax
is the object, then ax.axvline(x=0.220589956)
seems to work for me.– Joel
Jan 17 at 0:10
The arguments for axvline are scalar from 0 to 1, relative to the plot window. How do you draw a line at a given x or y position, such as 2.205... that was asked in this question?
– Edward Ned Harvey
Jul 29 at 15:25
The arguments for axvline are scalar from 0 to 1, relative to the plot window. How do you draw a line at a given x or y position, such as 2.205... that was asked in this question?
– Edward Ned Harvey
Jul 29 at 15:25
Looks like stackoverflow.com/questions/16930328/… has an answer.
plt.plot((x1,x2),(y1,y2))
– Edward Ned Harvey
Jul 29 at 15:30
Looks like stackoverflow.com/questions/16930328/… has an answer.
plt.plot((x1,x2),(y1,y2))
– Edward Ned Harvey
Jul 29 at 15:30
1
1
Please note, ymax and ymin should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. If you are using values beyond this range, you will need to translate the y positions with the correct ratio.
– Dylan Kapp
Nov 3 at 19:21
Please note, ymax and ymin should be between 0 and 1, 0 being the bottom of the plot, 1 the top of the plot. If you are using values beyond this range, you will need to translate the y positions with the correct ratio.
– Dylan Kapp
Nov 3 at 19:21
add a comment |
For multiple lines
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
how do we put a legend to the vertical line?
– Charlie Parker
Oct 17 '17 at 20:09
@CharlieParker consider asking a separate question. This part of matplotlib documentation may help you
– Ciprian Tomoiagă
Oct 19 '17 at 13:15
@CharlieParker An extra optionlabel='label'
does the work but you need to callplt.legend([options])
later
– kon psych
Dec 6 '17 at 3:31
add a comment |
For multiple lines
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
how do we put a legend to the vertical line?
– Charlie Parker
Oct 17 '17 at 20:09
@CharlieParker consider asking a separate question. This part of matplotlib documentation may help you
– Ciprian Tomoiagă
Oct 19 '17 at 13:15
@CharlieParker An extra optionlabel='label'
does the work but you need to callplt.legend([options])
later
– kon psych
Dec 6 '17 at 3:31
add a comment |
For multiple lines
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
For multiple lines
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
edited Mar 18 '16 at 16:12
smottt
2,71372939
2,71372939
answered Mar 18 '16 at 15:55
Qina Yan
57854
57854
how do we put a legend to the vertical line?
– Charlie Parker
Oct 17 '17 at 20:09
@CharlieParker consider asking a separate question. This part of matplotlib documentation may help you
– Ciprian Tomoiagă
Oct 19 '17 at 13:15
@CharlieParker An extra optionlabel='label'
does the work but you need to callplt.legend([options])
later
– kon psych
Dec 6 '17 at 3:31
add a comment |
how do we put a legend to the vertical line?
– Charlie Parker
Oct 17 '17 at 20:09
@CharlieParker consider asking a separate question. This part of matplotlib documentation may help you
– Ciprian Tomoiagă
Oct 19 '17 at 13:15
@CharlieParker An extra optionlabel='label'
does the work but you need to callplt.legend([options])
later
– kon psych
Dec 6 '17 at 3:31
how do we put a legend to the vertical line?
– Charlie Parker
Oct 17 '17 at 20:09
how do we put a legend to the vertical line?
– Charlie Parker
Oct 17 '17 at 20:09
@CharlieParker consider asking a separate question. This part of matplotlib documentation may help you
– Ciprian Tomoiagă
Oct 19 '17 at 13:15
@CharlieParker consider asking a separate question. This part of matplotlib documentation may help you
– Ciprian Tomoiagă
Oct 19 '17 at 13:15
@CharlieParker An extra option
label='label'
does the work but you need to call plt.legend([options])
later– kon psych
Dec 6 '17 at 3:31
@CharlieParker An extra option
label='label'
does the work but you need to call plt.legend([options])
later– kon psych
Dec 6 '17 at 3:31
add a comment |
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
- Each line is a separate plot object, which causes things to be very slow when you have many lines.
- When you create the legend each line has a new entry, which may not be what you want.
Instead you can use the following convenience functions which create all the lines as a single plot object:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
Good points. What aboutplt.vlines(xs,*plt.ylim())
?
– Vincenzooo
Mar 25 at 21:45
add a comment |
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
- Each line is a separate plot object, which causes things to be very slow when you have many lines.
- When you create the legend each line has a new entry, which may not be what you want.
Instead you can use the following convenience functions which create all the lines as a single plot object:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
Good points. What aboutplt.vlines(xs,*plt.ylim())
?
– Vincenzooo
Mar 25 at 21:45
add a comment |
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
- Each line is a separate plot object, which causes things to be very slow when you have many lines.
- When you create the legend each line has a new entry, which may not be what you want.
Instead you can use the following convenience functions which create all the lines as a single plot object:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
Calling axvline in a loop, as others have suggested, works, but can be inconvenient because
- Each line is a separate plot object, which causes things to be very slow when you have many lines.
- When you create the legend each line has a new entry, which may not be what you want.
Instead you can use the following convenience functions which create all the lines as a single plot object:
import matplotlib.pyplot as plt
import numpy as np
def axhlines(ys, ax=None, **plot_kwargs):
"""
Draw horizontal lines across plot
:param ys: A scalar, list, or 1D array of vertical offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
lims = ax.get_xlim()
y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
return plot
def axvlines(xs, ax=None, **plot_kwargs):
"""
Draw vertical lines on plot
:param xs: A scalar, list, or 1D array of horizontal offsets
:param ax: The axis (or none to use gca)
:param plot_kwargs: Keyword arguments to be passed to plot
:return: The plot object corresponding to the lines.
"""
if ax is None:
ax = plt.gca()
xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
lims = ax.get_ylim()
x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
return plot
edited Jun 19 at 15:40
answered Apr 17 '17 at 16:40
Peter
3,49142940
3,49142940
Good points. What aboutplt.vlines(xs,*plt.ylim())
?
– Vincenzooo
Mar 25 at 21:45
add a comment |
Good points. What aboutplt.vlines(xs,*plt.ylim())
?
– Vincenzooo
Mar 25 at 21:45
Good points. What about
plt.vlines(xs,*plt.ylim())
?– Vincenzooo
Mar 25 at 21:45
Good points. What about
plt.vlines(xs,*plt.ylim())
?– Vincenzooo
Mar 25 at 21:45
add a comment |
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
import matplotlib.pyplot as plt
xcoords = [0.1, 0.3, 0.5]
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
add a comment |
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
import matplotlib.pyplot as plt
xcoords = [0.1, 0.3, 0.5]
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
add a comment |
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
import matplotlib.pyplot as plt
xcoords = [0.1, 0.3, 0.5]
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
If someone wants to add a legend
and/or colors
to some vertical lines, then use this:
import matplotlib.pyplot as plt
xcoords = [0.1, 0.3, 0.5]
colors = ['r','k','b']
for xc,c in zip(xcoords,colors):
plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)
plt.legend()
plt.show()
Results:
answered Jul 16 at 13:19
seralouk
5,62522338
5,62522338
add a comment |
add a comment |
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
add a comment |
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
add a comment |
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
edited Dec 15 at 13:44
answered Sep 23 at 16:45
Bazingaa
10.2k21025
10.2k21025
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24988448%2fhow-to-draw-vertical-lines-on-a-given-plot-in-matplotlib%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown