How to draw vertical lines on a given plot in matplotlib?












146














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?










share|improve this question





























    146














    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?










    share|improve this question



























      146












      146








      146


      21





      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?










      share|improve this question















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 28 '14 at 18:44









      Gabriel

      4,74111322




      4,74111322










      asked Jul 28 '14 at 4:29









      Francis

      1,4333924




      1,4333924
























          5 Answers
          5






          active

          oldest

          votes


















          250














          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).






          share|improve this answer



















          • 6




            But how do I plot the line on a given axis object?
            – Eric
            Jun 27 '16 at 17:55






          • 4




            @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










          • 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



















          35














          For multiple lines



          xposition = [0.3, 0.4, 0.45]
          for xc in xposition:
          plt.axvline(x=xc, color='k', linestyle='--')





          share|improve this answer























          • 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 option label='label' does the work but you need to call plt.legend([options]) later
            – kon psych
            Dec 6 '17 at 3:31



















          15














          Calling axvline in a loop, as others have suggested, works, but can be inconvenient because




          1. Each line is a separate plot object, which causes things to be very slow when you have many lines.

          2. 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





          share|improve this answer























          • Good points. What about plt.vlines(xs,*plt.ylim())?
            – Vincenzooo
            Mar 25 at 21:45



















          7














          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:



          my amazing plot seralouk






          share|improve this answer





























            6














            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.






            share|improve this answer























              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
              });


              }
              });














              draft saved

              draft discarded


















              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









              250














              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).






              share|improve this answer



















              • 6




                But how do I plot the line on a given axis object?
                – Eric
                Jun 27 '16 at 17:55






              • 4




                @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










              • 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
















              250














              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).






              share|improve this answer



















              • 6




                But how do I plot the line on a given axis object?
                – Eric
                Jun 27 '16 at 17:55






              • 4




                @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










              • 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














              250












              250








              250






              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).






              share|improve this answer














              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).







              share|improve this answer














              share|improve this answer



              share|improve this answer








              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 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










              • 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




                But how do I plot the line on a given axis object?
                – Eric
                Jun 27 '16 at 17:55






              • 4




                @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










              • 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













              35














              For multiple lines



              xposition = [0.3, 0.4, 0.45]
              for xc in xposition:
              plt.axvline(x=xc, color='k', linestyle='--')





              share|improve this answer























              • 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 option label='label' does the work but you need to call plt.legend([options]) later
                – kon psych
                Dec 6 '17 at 3:31
















              35














              For multiple lines



              xposition = [0.3, 0.4, 0.45]
              for xc in xposition:
              plt.axvline(x=xc, color='k', linestyle='--')





              share|improve this answer























              • 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 option label='label' does the work but you need to call plt.legend([options]) later
                – kon psych
                Dec 6 '17 at 3:31














              35












              35








              35






              For multiple lines



              xposition = [0.3, 0.4, 0.45]
              for xc in xposition:
              plt.axvline(x=xc, color='k', linestyle='--')





              share|improve this answer














              For multiple lines



              xposition = [0.3, 0.4, 0.45]
              for xc in xposition:
              plt.axvline(x=xc, color='k', linestyle='--')






              share|improve this answer














              share|improve this answer



              share|improve this answer








              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 option label='label' does the work but you need to call plt.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










              • @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
















              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











              15














              Calling axvline in a loop, as others have suggested, works, but can be inconvenient because




              1. Each line is a separate plot object, which causes things to be very slow when you have many lines.

              2. 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





              share|improve this answer























              • Good points. What about plt.vlines(xs,*plt.ylim())?
                – Vincenzooo
                Mar 25 at 21:45
















              15














              Calling axvline in a loop, as others have suggested, works, but can be inconvenient because




              1. Each line is a separate plot object, which causes things to be very slow when you have many lines.

              2. 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





              share|improve this answer























              • Good points. What about plt.vlines(xs,*plt.ylim())?
                – Vincenzooo
                Mar 25 at 21:45














              15












              15








              15






              Calling axvline in a loop, as others have suggested, works, but can be inconvenient because




              1. Each line is a separate plot object, which causes things to be very slow when you have many lines.

              2. 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





              share|improve this answer














              Calling axvline in a loop, as others have suggested, works, but can be inconvenient because




              1. Each line is a separate plot object, which causes things to be very slow when you have many lines.

              2. 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






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jun 19 at 15:40

























              answered Apr 17 '17 at 16:40









              Peter

              3,49142940




              3,49142940












              • 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
















              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











              7














              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:



              my amazing plot seralouk






              share|improve this answer


























                7














                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:



                my amazing plot seralouk






                share|improve this answer
























                  7












                  7








                  7






                  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:



                  my amazing plot seralouk






                  share|improve this answer












                  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:



                  my amazing plot seralouk







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 16 at 13:19









                  seralouk

                  5,62522338




                  5,62522338























                      6














                      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.






                      share|improve this answer




























                        6














                        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.






                        share|improve this answer


























                          6












                          6








                          6






                          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.






                          share|improve this answer














                          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.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Dec 15 at 13:44

























                          answered Sep 23 at 16:45









                          Bazingaa

                          10.2k21025




                          10.2k21025






























                              draft saved

                              draft discarded




















































                              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.




                              draft saved


                              draft discarded














                              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





















































                              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







                              Popular posts from this blog

                              Costa Masnaga

                              Fotorealismo

                              Sidney Franklin