Plot with title which depends of variables - python

(Sorry for my english...)
I'm looking for a method to creat a plot.title which depends of my variables already defined at the begining.
I'm not asking you to make it for me. Just to help me to find documents, sites, forum or things like that. I haven't find in on Google and i don't know what to type coz english isn't my native language.
Currently, i'm showing a graph and creating a pdf. which also contain the graph, like that :
graphic = plt.figure(1)
plt.plot(ts, xs, label="Position")
plt.plot(ts, vs, label="Velocity")
plt.title("euler-k-10-c-0.1-dt-0.01")
plt.legend()
plt.xlabel("Time ts")
plt.ylabel("Valors of position xs and velocity vs")
plt.show()
pp = PdfPages("Graphics.pdf")
pp.savefig(graphic, dpi = 300, transparent = True)
pp.close()
What i want to, is to modify this line :
plt.title("euler-k-10-c-0.1-dt-0.01")
I'm supposed to enter the valors of k, c and dt variables, and i want to change the name of the graphic to make it concur with the valors choosen for these variables.
For example, my code ask to enter the valors of k, c and dt, so i enter :
k = 1 ; c = 0 ; dt = 0.1
Then the graph title is : euler-k-1-c-0-dt-0.1
Thank you very much !

The string entering the plot title can be composed of variables like any other string. In your particular case, something like
k = 1
c = 0
dt = 0.1
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
would do the job.
Here we've used formatted string literals; for other approaches to formatting a string, see e.g. this overview.

def make_plots(tx,xs,k,c,dt)
graphic = plt.figure(1)
plt.plot(ts, xs, label="Position")
plt.plot(ts, vs, label="Velocity")
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
plt.legend()
plt.xlabel("Time ts")
plt.ylabel("Valors of position xs and velocity vs")
plt.show()
pp = PdfPages("Graphics.pdf")
pp.savefig(graphic, dpi = 300, transparent = True)
pp.close()
Make a function and call it as often as you change your k,c and dt.

Ow ! Thank you, i didn't think i was that easy.
Make a function and call it as often as you change your k,c and dt.
Hum.. Yes thank you ! But that's not the point haha.
this :
plt.title(f'euler-k-{k}-c-{c}-dt-{dt}')
answer my question. It works ! Now i can do that :
k = int(input("Enter the valor of k : "))
And the valor of k that i entered is considered in the title of my graph !
Thanks !
PS : I was also wondering why there was an error message when i wrote it :
k = input("Enter the valor of k : ")
It's because the "thing" you write when the input is executed, is considered as a string, and not an integer or a float ! So i have to add int() to make it works !
Thank you guys, you're awesome !

Related

I want solve this Equations in python

I'm work with Python
it's simple (1.1*x)+(b+(b*0.1))=a this equation is what I want to solve.
I'm so newbie in this world so I having a problem with it
"a" and "b" is come with
int(input('factor a : '))
int(input('factor b : '))
How can I script this to make an calculator
I don't know what values ​​you would set the X to but you would just add the part of the equation and assemble it already in this code.
import math
a = int(input('factor a : '))
b = int(input('factor b : '))
print((b+(b*0.1))/a)
Depending on the kind of project that you have in mind you can use symbolic mathematics program to gather flexibility.
Here an example with sympy and a live shell to test it without installations.
from sympy import symbols, Eq, solve
# declare the symbols
x, a, b = symbols('x a b')
# set up the equation
eq = Eq((1.1*x)+(b+(b*0.1)), a)
# solve it (for hard ones there are several types of solvers)
sol = solve(eq, x)
# fix the free variables
extra_pars = {a.name: input('a:'), b.name: input('b')}
# replace into the expression
new_sol = sol[0].subs(extra_pars)
print(new_sol)

How is the signal formatted through this code?

The mat file contains the following:
data: [15×3000000 double]
data_length_sec: 600
sampling_frequency: 5000
channels: {1×15 cell}
This is the code to run:
preictal_tst = 'Patient_1/Patient_1_preictal_segment_0001.mat'
preictal_data = scipy.io.loadmat(preictal_tst)
preictal_array = preictal_data['preictal_segment_1'][0][0][0]
l = list(range(10000))
for i in l[::5000]:
print('Preictal')
i_secs = preictal_array[0][i:i+5000]
print(i_secs)
i_f, i_t, i_Sxx = spectrogram(i_secs, fs=5000, return_onesided=False)
print(i_f)
print(i_t)
print(i_Sxx)
i_SS = np.log1p(i_Sxx)
print(i_SS)
plt.imshow(i_SS[:] / np.max(i_SS), cmap='gray')
plt.show()
In the link is the image of how the signal looks like
https://i.stack.imgur.com/PSZSe.jpg
Its formatted by storing each of the following variables (i_f, i_t, i_Sxx to the outcome of the function spectrogram when (i_secs, fs=5000, return_onesided=False) is passed to it.
The question is really unclear though and I doubt that answer made it any clearer so please edit with a more specific question if you still have any

SyntaxError Invalid Token (GPS Coordinates)

First of all, I hope everyone's okay.
Now, my problem is that, when I want to assign 48,0162 as a y coordinate to a point, python tells me that the token is invalid (ik that 0 is a non-octal number and...).
So my question is, how can I write 48,0162 without inducting python systems in error ?
Thanks in advance,
Gwenn
#route
class Point():
"airfield coordinates"
LFST = Point()
LFST.x = 7,6305
LFST.y = 48,5353
LFGA = Point()
LFGA.x = 7,3555
LFGA.y = 480,162/10
def route(departurex,departurey,arrivalx,arrivaly):
vx=arrivalx-departurex
vy=arrivaly-departurey
scal=vx*vy+1
Floating point numbers should use a dot . not a comma ,. In some countries (like Sweden) we use commas as decimal separators, but in programming languages a . is generally used.
So LFST.y = 48,5353 should be LFST.y = 48.5353 for example.

Python string formatting exponential output

I'm trying to change the output of an exponential string formatting. I've fitted a curve to some data and would like to write these into the plot. Problem is, the x e-y format doesn't look nice, is there a posibility to change it so x * 10^-y?
Here is an example of the code I'm working with:
plt.plot(x, y, 'x', label = '$f(t) = {a:.0f} \cdot x + {b:.2e}$'.format(a = para[0], b = para[1])
a is some number bigger than 10000, that's why there is no need for decimalnumbers, but b is around 10^-7. Writing it as a float is spacewasting for the leading 0s, but the e^-7 doesn't look nice for publishing, that why I would like to change the output of the e-formatter, so it gives \cdot 10^{-7} (the \cdot {} for LaTeX) back.
Thanks
I would suggest you write an ad-hoc function to format the number in the output you want, something like this:
import numpy as np
def myformat(x):
myexp = np.floor(np.log10(x))
xout = x*10**(-myexp)
strout = "{:.2f} \times 10^{}".format(xout, myexp)
return strout
All, that need to be formated in LaTex style, must be wrapped with $ sign:
label='$f(t)$ = $x$ $\cdot$10$^-$$^7$'
Sign ^ makes aftergoing char as superscript (x$^5$ will give x to the power of 5) and _ is using for subscript (x$_5$ will give you x with index 5)

Nested Anova in python with Spm1d. Can't print f statistics and p values

I'm looking for a simple solution to perform multi-factor ANOVA analysis in python. A 2-factor nested ANOVA is what I'm after, and the SPM1D python module is one way to do that, however I am having an issue.
http://www.spm1d.org/doc/Stats1D/anova.html#two-way-nested-anova
for any of the nested approach examples, there is never any F-statistic or p_values printed, nor can I find any way to print them or send them to a variable.
To go through the motions of running one of their examples, where B is nested inside A, with Y observations:
import numpy as np
from matplotlib import pyplot
import spm1d
dataset = spm1d.data.uv1d.anova2nested.SPM1D_ANOVA2NESTED_3x3()
Y,A,B = dataset.get_data()
#(1) Conduct ANOVA:
alpha = 0.05
FF = spm1d.stats.anova2nested(Y, A, B, equal_var=True)
FFi = FF.inference(0.05)
print( FFi )
#(2) Plot results:
pyplot.close('all')
FFi.plot(plot_threshold_label=True, plot_p_values=True)
pyplot.show()
The only indication of statistical significance provided is whether the h0 hypothesis is rejected or not.
> print( FFi )
SPM{F} inference list
design : ANOVA2nested
nEffects : 2
Effects:
A z=(1x101) array df=(2, 6) h0reject=True
B z=(1x101) array df=(6, 36) h0reject=False
In reality, that should be enough. However, in science, scientists like to think of something as more or less significant, which is actually kind of crap... significance is binary. But that's how they think about it, so I have to play along in order to get work published.
The example code produces a matplotlib plot, and this DOES have the f statistic and p_values on it!
#(2) Plot results:
pyplot.close('all')
FFi.plot(plot_threshold_label=True, plot_p_values=True)
pyplot.show()
But I can't seem to get any output which prints it.
FFi.get_p_values
and
FFi.get_f_values
produce the output:
<bound method SPMFiList.get_p_values <kabammi edit -- or get_f_values> of SPM{F} inference list
design : ANOVA2nested
nEffects : 2
Effects:
A z=(1x101) array df=(2, 6) h0reject=True
B z=(1x101) array df=(6, 36) h0reject=False
So I don't know what to do. Clearly the FFi.plot class can access the p_values (with plot_p_values) but FFi.get_p_values cant!!? Can anyone lend a hand?
cheers,
K
The easiest way to get the p values is to use the get_p_values method that you mention, you just need to call the method by adding () to the end.
p = FFi.get_p_values()
print(p)
This yields:
([0.016584151119287904], [])
To see more detailed information for each effect in 2+-way ANOVA, including p values, use print along with the individual F statistics like this:
print( FFi[0] )
print( FFi[1] )
The first print statement will produce output like this:
SPM{F} inference field
SPM.effect : Main A
SPM.z : (1x101) raw test stat field
SPM.df : (2, 6)
SPM.fwhm : 11.79254
SPM.resels : (1, 8.47993)
Inference:
SPM.alpha : 0.050
SPM.zstar : 24.30619
SPM.h0reject : True
SPM.p_set : 0.017
SPM.p_cluster : (0.017)
You can retrieve the clusters' p values like this:
p = [F.p for F in FFi]
which gives the same result as calling get_p_values.
Note that there are no p values in this case for FFi[1] because the test statistic fails to cross the alpha-defined threshold (see the "Main B" panel in the figure above). If you need to report p values in this case as well, one option is simply to use "p > alpha". More precise p value are available parametrically up until about p = 0.5, but larger p values than that are not very accurate using parametric methods, so if you need p values for all cases consider using the nonparametric version: spm1d.stats.nonparam.anova2nested.

Categories