Search code examples
pythonmatplotlibwidth

In Pyplot, How can we change the line width of a plot once it is already plotted?


Consider the following python module 'plot_figure.py' defining PlotFigure(). Note that it is a pseudo-code.

import matplotlib.pyplot as plt

def PlotFigure(x)
  # Some other routines..
  plt.plot(x)
  # Some other routines..

I would like to call plot_figure.PlotFigure, but after plotting a figure, I would like to change the line widths of this figure. Even though PlotFigure() may include other routines, the lines in the figure are plotted using plt.plot() as shown in the above pseudo-code.

The following is the code that calls plot_figure.PlotFigure()

#!/usr/bin/python
import matplotlib.pyplot as plt
import plot_figure
x_data = [ # some data ]
plot_figure.PlotFigure(x_data)

#***I would like to change the line width of the figure here***

plt.show()

I know that I can get the figure handle using fig = plt.gcf(), but plt.setp(fig, linewidth=2) doesn't work.

Could anyone give some suggestion on this?


Solution

  • First let me note that the generic way to set the linewidth (or any other plot parameter) would be to give it as an argument to the plot command.

    import matplotlib.pyplot as plt
    
    def PlotFigure(x, **kwargs):
        # Some other routines..
        plt.plot(x, linewidth=kwargs.get("linewidth", 1.5) )
        # Some other routines..
    

    and the call

    plot_figure.PlotFigure(x_data, linewidth=3.)
    

    If this really is not an option, you'd need to get the lines from the figure.
    The easiest case would be if there was only one axes.

    for line in plt.gca().lines:
        line.set_linewidth(3.)