'Class attributes for returning a table and plot in python
I have a parent class in which I have defined functions to plot a graph and create a table. I have then created attributes which should return the plot and table i.e. self.plot and self.table. However, currently, the plot is displayed as soon as I create an instance of the parent class, instead of only when I have printed self.plot. Also, the table is only displayed if I do e.g. table = self.table then type table. I have explained how I would like to get the plot and table as an output below.
Code for creating the dataset and parent class:
import numpy as np
import pandas as pd
import math
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.dates as md
import matplotlib.ticker as ticker
from datetime import datetime, timedelta
# create dataframes that will be used
date_today = datetime.now()
days = pd.date_range(date_today, date_today + timedelta(1000), freq='D')
np.random.seed(seed=1111)
data_a = np.random.randint(10, high=50, size=len(days))
dataframe = pd.DataFrame({'date': days, 'a': data_a})
dataframe = dataframe.set_index('date')
# define a parent class
class ParentClass:
def __init__(self, df):
# define attributes to return the plot and table
self.df = df
self.plot = self.return_plot()
self.table = self.return_table()
return
def return_plot(self):
fig = plt.figure()
ax = plt.axes()
l_plot = sns.lineplot(data=self.df['a'], color="b", ax=ax)
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.margins(x=0)
plt.show()
return
def return_table(self):
# create a table
index = ['sum', 'mean', 'value_1', 'value_2']
data = [self.df['a'].sum(), self.df['a'].mean(), 4, 5]
table = pd.DataFrame(data=data, index=index, columns=['stats'])
# set style
header = {'selector': 'th', 'props':
[('background-color', 'blue'), ('color', 'white')]}
table = table.style.set_table_styles([header])
table
return table
Current code for creating an instance of the class and returning the plot and table:
instance = ParentClass(dataframe)
table = instance.table
table
How I would like to be able to create an instance of the parent class and return the plot and table:
instance = ParentClass(dataframe)
plot = instance.plot
table = instance.table
print(plot)
print(table)
I would be grateful for any help!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


