Line With Fit

../../../../_images/line_with_fit.png
Data fitted to a + b * x ** c
OrderedDict([('a', 1.1647414733130381), ('b', 0.2642691329552675), ('c', 3.062474643906167)])
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Plot a line and fit a curve.
# This example creates a plot and a fitted curve with a custom expression.

# The line data.
position = [
    0.        , 0.10869565, 0.2173913 , 0.32608696, 0.43478261, 0.54347826,
    0.65217391, 0.76086957, 0.86956522, 0.97826087, 1.08695652, 1.19565217,
    1.30434783, 1.41304348, 1.52173913, 1.63043478, 1.73913043, 1.84782609,
    1.95652174, 2.06521739, 2.17391304, 2.2826087 , 2.39130435, 2.5
] * Angstrom

energy = [
    0.45292599, 1.29450797, 0.90624412, 0.84560608, 0.64978286, 0.71261064,
    1.67142063, 1.85748419, 1.85836352, 1.16352569, 2.03563087, 2.31325527,
    1.43093584, 2.01424388, 1.86664553, 2.11120909, 2.42706843, 2.12015567,
    2.62814134, 4.41887562, 4.69864691, 4.73923266, 4.47810888, 5.0582645
] * eV

# Create a model.
model = Plot.PlotModel(Angstrom, eV)
model.title().setText('Fit a Line')
model.xAxis().setLabel('Length')
model.xAxis().setAutoscalePadding(0.07, 0.07)
model.yAxis().setLabel('Energy')

model.legend().setVisible(True)

# Create line.
line = Plot.Line(position, energy)
line.setLabel('Line')
line.setMarkerStyle('o')
line.setMarkerFaceColor('mediumpurple')
line.setMarkerEdgeColor('mediumpurple')
line.setLineStyle(None)

# Create fit and add to line.
fit = Plot.CurveFit('a + b * x ** c')
line.addItem(fit)

# By default the fit range contains the entire line. The range can be modified
# interactively by calling Plot.show(model) and dragging the limits, or it can
# be done in script:
fit.setBounds(0.1 * Angstrom, 2.4 * Angstrom)

# Get results.
print('Data fitted to ' + fit.expression())
print(fit.parameters())

# Add line to plot.
model.addItem(line)

# Autoscale limits.
model.setLimits()

# Show the plot for interactive editing.
Plot.show(model)

# Save the plot (can also be saved to svg, pdf, jpeg or hdf5).
Plot.save(model, 'line_with_fit.png')

References: Plot.PlotModel, Plot.save, Plot.show, Plot.CurveFit, Plot.Line.

↩ Go back to Plots