Home > other >  matplotlib plot a numpy array as many lines with a single label
matplotlib plot a numpy array as many lines with a single label

Time:09-13

I have a list of list of data to plot as many lines. Basically: [dataset1, dataset2]. But the point is that I want to put a single label in common to all these lines. Here is an example:

data = np.array([[1, 2, 3, 4, 5, 6], [1, 5, 3, 8, 9, 6]])
plt.plot(np.transpose(data), c = "b", label="hello stack")
plt.legend()
plt.show()

enter image description here

A way to do that can be to convert the numpy array into a list of list, then iterate through each datasets too plot them separately, and giving a label to the first one only. But in order to have a more fancy code and for my personal curiosity, I'm looking for a way to do it by plotting the numpy array directly. Do you know a way to do that ?

CodePudding user response:

The solution was simple finally: By giving a list of label, you give a specific label for each dataset in the numpy array. And if a value of one of these labels is None, then the dataset will have no label. So you can add your label to a list of None values:

data = np.array([[1, 2, 3, 4, 5, 6], [1, 5, 3, 8, 9, 6]])
labels = ["solved"]   [None] * (data.shape[0] - 1)
plt.plot(np.transpose(data), c="b", label=labels)
plt.legend()
plt.show()

enter image description here

Edited using the version of @paime

  • Related