Python Forum
Add label to matplotlib function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Add label to matplotlib function
#1
I am learning a bit about matplotlib here, their own webpage.

To quote the matplotlib page: "Typically one finds oneself making the same plots over and over again, but with different data sets, which leads to needing to write specialized functions to do the plotting. The recommended function signature is something like:"

What I want to do is add a legend. In the previous example of a linear, quadratic and cubic plot, that was achieved like this:

ax.plot(x, x, label='linear')  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic')  # ... and some more.
ax.legend()  # Add a legend.
This code is from their webpage, I just changed it slightly.

How can I add label to this function and so display the legend?? I've tried various things, but I just get errors.

def myApp():
    import matplotlib.pyplot as plt
    import numpy as np

    def my_plotter(ax, data1, data2, param_dict):
        """
        A helper function to make a graph

        Parameters
        ----------
        ax : Axes
            The axes to draw to

        data1 : array
           The x data

        data2 : array
           The y data

        param_dict : dict
           Dictionary of kwargs to pass to ax.plot

        Returns
        -------
        out : list
            list of artists added
            
        """
        # if you don't set the ranges, the range shown will be a little more than the maximum value
        #ax.set_xlim(0, 10)  # set the X range
        #ax.set_ylim(0, 10)  # set the Y range
        
        ax.set_xlabel('my X axis')
        ax.set_ylabel('my Y label')
        ax.set_title('Some Random Plot')
        #ax.legend()  # Add a legend.
        ax.grid(True)
        out = ax.plot(data1, data2, **param_dict)
        return out
    
    
    data1, data2, data3, data4 = np.random.randn(4, 10)
    fig, ax = plt.subplots(1, 1)
    my_plotter(ax, data1, data2, {'marker': 'x'})    
    plt.show()
Reply
#2
It would be helpful, if you provided error-trace here.
However, you can try the following changes to your code:

...
        out = ax.plot(data1, data2, **param_dict)   # you don't need to assign out variable, you can remove `return out` and `out=`
        ax.legend()
        return out
...

my_plotter(ax, data1, data2, {'marker': 'x', 'label': 'one'})  

....
# Somewhere:
myApp()
Reply
#3
EDIT: Sorry, didn't think to put the original error: No handles with labels found to put in legend.

Thank you!

First it wouldn't work with:

my_plotter(ax, data1, data2, {'marker': 'x', 'label': one})
NameError: name 'one' is not defined

I changed one for 'randomplot', now it shows up great!

Thanks a lot!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Matplotlib: How do I convert Dates from Excel to use in Matplotlib JaneTan 1 3,245 Mar-11-2021, 10:52 AM
Last Post: buran
  Use Function in Tkinter Label bigfatgreedykat 0 2,668 Jan-10-2018, 10:03 AM
Last Post: bigfatgreedykat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020