Line With Fit¶
Data fitted to a + b * x ** c
OrderedDict([('a', 1.164741495616713), ('b', 0.26426911018527083), ('c', 3.06247474310537)])
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 60 61 62 63 64 65 | # Plot a line and fit a curve.
# This example creates a plot and a fitted curve with a custom expression.
# The fit expression and fit parameters are then displayed in an
# AttributesLabel in the plot.
# 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.framing().setTitle('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('Data')
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)
# Add an AttributesLabel to display the curve fit attributes in the plot.
attributes = Plot.AttributesLabel(1.25 * Angstrom, 3.5 * eV)
fit.addItem(attributes)
# 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.AttributesLabel, Plot.CurveFit, Plot.save, Plot.Line, Plot.show.
↩ Go back to Plots