0

I have a list of objects belonging to the class Config defined as the following:

class Config: 
    def __init__(self,atoms,pH,pOH,proton_count,conjugate_base_count,timestep,totalEnergy,pressure,temperature,nascent_oxy):
        self.atoms=atoms
        self.pH=pH
        self.pOH=pOH
        self.proton_count=proton_count
        self.conjugate_base_count=conjugate_base_count
        self.nascent_oxy=nascent_oxy
        self.timestep=timestep
        self.totalEnergy=totalEnergy
        self.pressure=pressure
        self.temperature=temperature

I want to plot the pH, pOH, proton_count, nascent_oxy against the timestep. One way is to make a list out of all the attributes and do the following :

list1=[x.pH for x in configs]
list1=[x.pOH for x in configs]

Is there a more efficient way of doing this - in terms of memory and reducing the hardcoding?

1 Answer 1

1

The easiest way to reduce the amount of code is to wrap the attribute-getting process in a function:

def get_attribute_values(list_of_objects, attribute):
    return [getattr(obj, attribute) for obj in list_of_objects]

Then when you construct your plot, you can loop over your list of objects to dynamically add data to it:

import matplotlib.pyplot as plt

attributes = ['ph', 'pOH', 'proton_count', 'conjugate_base_count', 'nascent_oxy', 'totalEnergy', 'pressure', 'temperature']
x_axis = get_attribute_values(configs, 'timestep')   
for attr in attributes:
    y_axis = get_attribute_values(configs, attr)
    plt.plot(x_axis, y_axis, label=attr)
plt.xlabel('timestep')
plt.ylabel('values')
plt.title('Multi-line plot')
plt.legend()
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.