I have been using ipython (Jupyter) notebook for my tasks with R and Python. Recently, I explored R Notebook and I found the kind of functionalities I wish they were in Jupyter Notebook implemented in R Notebook. So, I want to switch to R Notebook. However, when using Python in R Notebook, I could not cache the python results and use output from one chunk in another chunk. Further, I am not able to generate the python plots inline. It gives me plots in a new window, not in the notebook itself. To just provide some reproducible code, the code below works fine and gives an output if you put it in a single chunk but if you divide it into a couple of chunks, you cannot call outputs from one chunk in another chunk. The figure also pops up in a new window.
```{python}
# Import necessary modules
from sklearn import datasets
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
# Load the digits dataset: digits
digits = datasets.load_digits()
# Create feature and target arrays
X = digits.data
y = digits.target
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42, stratify = y)
# Setup arrays to store train and test accuracies
neighbors = np.arange(1, 9)
train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
# Loop over different values of k
for i, k in enumerate(neighbors):
# Setup a k-NN Classifier with k neighbors: knn
knn = KNeighborsClassifier(n_neighbors = k)
# Fit the classifier to the training data
knn.fit(X_train,y_train)
#Compute accuracy on the training set
train_accuracy[i] = knn.score(X_train, y_train)
#Compute accuracy on the testing set
test_accuracy[i] = knn.score(X_test, y_test)
# Generate plot
plt.title('k-NN: Varying Number of Neighbors')
plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')
plt.legend()
plt.xlabel('Number of Neighbors')
plt.ylabel('Accuracy')
plt.show()
```
The plot below shows up in a new window. Not inline in the Notebook.