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
答案 0 :(得分:0)
显然,这是一个Python控制台输出渲染。考虑将输出重定向(借用@Jfs's answer)到字符串值中,然后像R一样替换漂亮打印的换行符:
...
# 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