Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to plot the running average of my graph and calculate average value (±) using python

I have a file (file.xvg), of which I plot the result using matplotlib and numpy (version Python 3.9.12).
here my script:

import matplotlib.pyplot as plt
import numpy
import numpy as np
from scipy import signal

x, y = numpy.loadtxt("file.xvg", unpack=True)

fig = plt.figure(figsize=(13,8))
ax = fig.add_subplot(111)

ax.plot(x, y, color="k", linestyle='solid', linewidth=0.8)

ax.set_xlabel("Times (ps)", fontweight='bold', fontsize = 18, labelpad=3)
ax.set_ylabel("Pressures (bar)", fontweight='bold', fontsize = 18, labelpad=3)

plt.show()

and the file.xvg

   0.0000000    0.0287198
   0.0100000    0.0655187
   0.0200000    0.0665948
   0.0300000    0.0676697
   0.0400000    0.0797021
   0.0500000    0.0883750
   0.0600000    0.0824649
   0.0700000    0.0726798
   0.0800000    0.0749663
   0.0900000    0.0746549
   0.1000000    0.0767466
   0.1100000    0.1051620
   0.1200000    0.0846607
   0.1300000    0.0746683
   0.1400000    0.0744862
   0.1500000    0.0913541
   0.1600000    0.0844304
   0.1700000    0.0750595
   0.1800000    0.0783450
   0.1900000    0.0869718
   0.2000000    0.0969575
   0.2100000    0.0924280
   0.2200000    0.0759971
   0.2300000    0.0704025
.
.
.

I wanted to plot the running average as in the figure below:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The average value of the plot figure is 7.5 ± 160.5 bar

>Solution :

You have to calculate your running avg (selecting a window of values rang) for both your x and y array:

x_avg = []
y_avg = []
rang = 10
for ind in range(len(y)-rang +1):
    y_avg.append(np.mean(y[ind:ind+rang]))
    x_avg.append(np.mean(x[ind:ind+rang]))

ax.plot(x_avg, r_avg, color="red", linestyle='solid', linewidth=0.8)

PS: what a throwback, is that GROMACS? 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading