I am trying to write python code using rmarkdown
in bookdown
. The python code is ok. The problem is when the book pdf is generated, some long python codes and sometimes some python codes' output are outside of the pdf page and therefore they are not visible. Please see the images below.
In the image you can see the print ('The total number of rows and columns in the dataset is {} and {} respectively.'.format(iris_df.shape[0],iris_df.shape[1]))
function code is not fully visible, but the output is visible. Another case, for new_col = iris_df.columns.str.replace('\(.*\)','').str.strip().str.upper().str.replace(' ','_')
code, the whole code line is not visible and also the output of the code. The same issue is in sns.scatterplot ()
line of code.
I am just wondering whether there is anyway in bookdown
pdf, both the code and the associated output will not be outside of the pdf page.
Note: I tried to write python code in rmarkdown
in multiple lines, but it did not work and most cases the codes are not executed when python codes are written in multiple lines in rmarkdown
.
Here is the code that I used to generate the output in the image
from sklearn import datasets
iris = datasets.load_iris()
iris.keys()
iris_df = pd.DataFrame (data = iris.data, columns = iris.feature_names)
iris_df['target'] = iris.target
iris_df.sample(frac = 0.05)
iris_df.shape
print ('The total number of rows and columns in the dataset is {} and {} respectively.'.format(iris_df.shape[0],iris_df.shape[1]))
iris_df.info()
new_col = iris_df.columns.str.replace('\(.*\)','').str.strip().str.upper().str.replace(' ','_')
new_col
iris_df.columns = new_col
iris_df.info()
sns.scatterplot(data = iris_df, x = 'SEPAL_LENGTH', y = 'SEPAL_WIDTH', hue = 'TARGET', palette = 'Set2')
plt.xlabel('Sepal Length'),
plt.ylabel('Sepal Width')
plt.title('Scatterplot of Sepal Length and Width for the Target Variable')
plt.show()