I am learning how to create and modify plots using matplotlib in Jupyter Notebook. I added the following magic function and import statements right at the beginning of the notebook:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
Then, I created a cell and added all the following code:
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = x
plt.figure()
plt.scatter(x[:2], y[:2], s=100, c='red', label='Red data')
plt.scatter(x[2:], y[2:], s = 100, c='blue', label='Blue data')
plt.xlabel('This is my x label')
plt.ylabel('This is my y label')
plt.title('This is my plot title')
The plot itself seems fine in this case, although I don't understand why the additional Text(0.5, 1.0, 'This is my plot title')
line gets added, and nothing about the xlabel and ylabel text objects.
Now I find it rather impractical to always have to force every command pertaining to a plot into one cell. I would like to be able to create the basic plot in one cell and add labels and legend to it in a different cell (and later on do other manipulations on the plot, this is not a topic for this question though). To achieve this, I would need to reference the plot created in the first cell - for this, I used plt.gcf()
. However, when I run the following code, Python / matplotlib / Jupyter treats the different cells as different plots entirely. (Note: the dashed separations indicate different Jupyter Notebook cells.)
plt.figure()
plt.scatter(x[:2], y[:2], s=100, c='red', label='Red data')
plt.scatter(x[2:], y[2:], s = 100, c='blue', label='Blue data')
#-------------------------------------------------------------
plt.gcf()
plt.xlabel('This is my x label')
plt.ylabel('This is my y label')
plt.title('This is my plot title')
#-------------------------------------------------------------
plt.gcf()
plt.legend(loc=4, frameon=False, title='Legend')
I tried changing %matplotlib inline
to the apparently more modern %matplotlib notebook
but it didn't help. I also tried removing the plt.gcf()
rows from the beginning of the cells but I still got the same output.
Edit My versions are:
- Python 3.7.0
- matplotlib 3.2.2
- ipykernel 5.2.1
- ipywidgets 7.5.1
- jupyter 1.0.0
- jupyter_core 4.6.3
- jupyter_client 6.1.6
- notebook 6.0.3
- Windows 10