3

In short, I have (a couple of days worth of) glucose values plotted against their timestamps. I have written a function which then layers the glucose values on the same x-axis so I can look for glucose trends. Ultimately, that means that glucose data from a couple of days is plotted with different lines, resulting in the graph below:

enter image description here

Currently, the label says 'Glucose reading' for every color. I am looking to set the label in a way so when the data is being plotted it shows the dates (2019-11-21, 2019-11-22) and so on. I'm really not sure how to do it since I've never dealt with matplotlib legends below and I couldn't really find any useful solutions.

Any guidance would be much appreciated!

EDIT 1:

I am using pandas dataframe. Minimal code example - My legend is positioned in a plotting function like so:

def plotting_function(x, y, isoverlay = False):

    years_fmt = mdates.DateFormatter(' %H:%M:%S')
    ax = plt.axes()
    ax.xaxis.set_major_formatter(years_fmt)
    dates = [date.to_pydatetime() for date in x]

    if isoverlay:
        plt.plot(x, y, label= "Glucose reading" )
    else:
        plt.plot(x, y, 'rs:', label="Glucose reading")

    plt.xlabel("Time of readings")
    plt.ylabel("Glucose readings in mmol/L")

    plt.legend(ncol=2)
    plt.title("Glucose readings plotted against their timestamps")
JohanC
  • 71,591
  • 8
  • 33
  • 66
  • 1
    Step one: post a minimal code example that shows how exactly the plot and its legend are created. There are many ways to create such a plot and such a legend. Is this a dataframe plotted using pandas? – JohanC May 01 '20 at 18:27
  • Thank you! Added a minimal code example. I am using pandas dataframe. – Stefani Dimitrova May 01 '20 at 20:18
  • How are you calling that function? Please [provide a reproducible copy of the DataFrame with `to_clipboard`](https://stackoverflow.com/questions/52413246/provide-a-reproducible-copy-of-the-dataframe-with-to-clipboard/52413247#52413247). Otherwise, if the answer from @JohanC is sufficient, accept his answer or leave a comment. – Trenton McKinney May 01 '20 at 21:52

1 Answers1

0

In the plotting function you could add a list of the labels for the legend as an extra parameter and give that to plt.legend().

Here is a minimal example to show how it could work:

import numpy as np
import matplotlib.pyplot as plt

def plotting_function(x, y, labels):
    plt.plot(x, y)
    plt.legend(labels, ncol=2)

N = 100
K = 9
x = np.arange(N)
y = np.random.normal(.05, .2, (N, K)).cumsum(axis=0) + np.random.uniform(1, 10, K)
labels = [f'label {i + 1}' for i in range(K)] # as a test: ['label 1', 'label 2' ,...]
# labels = ['2019-11-21', '2019-11-22', ...] # this is another example, how dates could be used
plotting_function(x, y, labels)

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • Ah, thank you! I think this is going to solve my problem. However, I am a bit confused regarding the labels = [f'label {i + 1}' for i in range(K)] line. What does 'f' stand for, because when I tried it, I got the following error: 'TypeError: only integer scalar arrays can be converted to a scalar index' – Stefani Dimitrova May 02 '20 at 00:25
  • You didn't post the code that calls 'plotting_function', so it is unclear what the best way would be to form the labels. Strings with an f in front ([f-strings](https://realpython.com/python-f-strings/)) are a handy new way to format values into a string. If you edit your post and create a small example how your data is organized and which date types are involved, people can look into how to format these to form a list of labels (a list of 9 strings in the example of the question). I edited my answer with an example of how the date labels could look like. – JohanC May 02 '20 at 00:49
  • I managed to configure a few lines from your example to my case! Thank you so much. – Stefani Dimitrova May 02 '20 at 11:49