Home > Enterprise >  How to plot results from functions?
How to plot results from functions?

Time:03-13

Having data in Series and trying to calculate certain values but when trying to plot them it does not work.

# import pandas as pd
import pandas as pd
  
# import numpy as np
import numpy as np
  
# simple array
data = np.array([0,0,1,1,1])
  
ser = pd.Series(data)
print('The mean is '   str(ser.mean()))

# find the variance
print('The variance is '   str(ser.var()))

ser.mean().plot.bar(rot=0) # Attempt to use barplot
ser.var().plot.bar(rot=0) # Attempt to use barplot

The above give the following error:

The mean is 0.6
The variance is 0.30000000000000004
AttributeError: 'float' object has no attribute 'plot'

It would be cool to show both values in a single plot also.

CodePudding user response:

The function which you are trying to use is only available for pandas DataFrame/Series, but you can't use it to plot 'float', 'int' values.

For this case, either store the mean and variance values to an dataframe/series as follows

d = [ser.mean(),ser.var()]
df = pd.Series(d) #pd.DataFrame(d) also works
ax = df.plot.bar(rot=1)
ax.set_xticklabels(['Mean','Variance'])

or you can use other packages to plot a bar chart.

  • Related