0

I am attempting to plot a stem and leaf plot in python with rpy2, the plot shows in my output but it is not arranged well, as you can see the output has unnecessary breaks in it when some of the output should all be on the same line (see below). How can a remedy this?

import pandas as pd
import numpy as np
from rpy2.robjects import r, pandas2ri, numpy2ri

pandas2ri.activate()  # Lets me convert pandas data frame to r
numpy2ri.activate()  # Lets me use numpy arrays in r functions s

df = pd.DataFrame(r['iris'])  # Convert r's iris data set to a pandas 

#  Set column names
attributes = ["sepal_length", "sepal_width", "petal_length", 
"petal_width", "class"]
df.columns = attributes

# Get list of sepal widths of versicolor
df_versicolor = df.loc[df['class'] == "versicolor"]
versicolor_sepal_width = df_versicolor["sepal_width"].tolist()
versicolor_sepal_width = np.array(versicolor_sepal_width) 


# Stem and leaf plot
r_stem_and_leaf = r['stem']
stem = r_stem_and_leaf(example)

And the output, which is not aligned well

       The decimal point is 
1 digit(s) to the left of the |


  20 | 
0


  22 | 
0
0
0
0
0


  24 | 
0
0
0
0
0
0
0


  26 | 
0
0
0
0
0
0
0
0


  28 | 
0
0
0
0
0
0
0
0
0
0
0
0
0


  30 | 
0
0
0
0
0
0
0
0
0
0
0


  32 | 
0
0
0
0


  34 | 
0
Oamar Kanji
  • 1,824
  • 6
  • 24
  • 39

1 Answers1

0

Apparently, that is a Python console output rendering. Consider redirecting the output (borrowing @Jfs's answer) into a string value and then replace line breaks for the pretty print as R does:

...
# Stem and leaf plot    
from io import StringIO
from contextlib import redirect_stdout

with StringIO() as buf, redirect_stdout(buf):
    stem = r['stem'](df_versicolor['sepal_width'])  # DF COLUMN CAN BE USED
    output = buf.getvalue()

print(output.replace('\n','').replace('  ', '\n'))

# The decimal point is 1 digit(s) to the left of the |
# 20 | 0
# 22 | 00000
# 24 | 0000000
# 26 | 00000000
# 28 | 0000000000000
# 30 | 00000000000
# 32 | 0000
# 34 | 0
Parfait
  • 104,375
  • 17
  • 94
  • 125