A Byte of PhysicsLogo

Electric field visualization

An electric field is a vector assigned to every valid point in space. A visualization cannot draw infinitely many vectors, so it samples the field and encodes selected values as arrows, field lines, colors, or equipotential contours. Those marks are representations of the field, not the field itself.

Every representation makes choices about spacing, length scale, color, seed locations, viewing plane, and singularities. A scientifically useful diagram makes those choices visible and keeps exact numerical values separate from display geometry.

The vector field comes first

For a point charge \(q\) at \(\mathbf r_s\), the electric field at observation point \(\mathbf r\) is

\[\mathbf E(\mathbf r) =k_eq\frac{\mathbf r-\mathbf r_s} {\lVert\mathbf r-\mathbf r_s\rVert^3}\]

The calculation returns components and a unit, such as newtons per coulomb. A display then maps that vector to a visible mark. The calculation should not know the arrow's pixel length, line thickness, or color.

For several sources, superposition gives

\[\mathbf E(\mathbf r)=\sum_i\mathbf E_i(\mathbf r)\]

Sampling and rendering must occur after the vector sum. Drawing one arrow per source at the same point can show contributions, but it does not replace the resultant field unless the vector addition is also visible.

Arrow plots encode direction and magnitude

At each grid point, an arrow normally points in the direction of \(\mathbf E\). A linearly scaled arrow might use

\[L_{\mathrm{display}}=\alpha\lVert\mathbf E\rVert\]

Here \(L_{\mathrm{display}}\) is a screen length and \(\alpha\) converts field magnitude into that length. This is a visual mapping, not a physical equation.

Point-charge magnitudes vary rapidly, so linear scaling can make distant arrows invisible while arrows near a source dominate the page. Common alternatives include normalizing all arrow lengths, using a logarithmic scale, or imposing a cap:

\[L_{\mathrm{display}} =\min\left(\alpha\lVert\mathbf E\rVert,L_{\max}\right)\]

A cap improves readability but hides differences above the threshold. Two maximum-length arrows may represent very different field magnitudes. The legend must say that clipping occurred, and a selected-probe readout should report the uncapped components and magnitude.

Normalized arrows show direction only. They must not be interpreted as equal physical field strengths.

Grid density is not field strength

An arrow grid samples chosen coordinates. Increasing grid density places more arrows on the page; it does not strengthen the field. A coarse grid can miss a null point or a rapid direction change, while an excessively dense grid can become unreadable through overlap.

Convergence should be checked at fixed physical points. If changing the display grid changes the calculated field at an unchanged probe, analysis and rendering have been incorrectly coupled.

For a rectangular two-dimensional slice, state the plane and which component is omitted. A diagram in the horizontal-vertical plane may show \((E_x,E_y)\) while hiding \(E_z\). A two-dimensional picture of a point charge is a slice through a three-dimensional inverse-square field, not a two-dimensional inverse-square universe.

Field lines are integral curves

A field line is a curve whose tangent points along the electric field. If

\(\mathbf r(s)\)

describes the curve, one convenient parameterization obeys

\[\frac{d\mathbf r}{ds} =\frac{\mathbf E(\mathbf r)} {\lVert\mathbf E(\mathbf r)\rVert}\]

This equation determines direction, but a drawing still needs seed points and a numerical integration rule. Different seed choices produce different-looking line sets for the same field. The number of drawn lines is conventional, although diagrams often choose line density to suggest relative magnitude.

Electric field lines do not cross at a regular point. A crossing would assign two different tangent directions to the single field vector at that point. At a true null where \(\mathbf E=0\), the direction is undefined, so streamline integration needs a stopping rule.

In electrostatics, lines point away from positive charge and toward negative charge. They can also enter or leave the plotted boundary. They do not form closed loops because an electrostatic field is conservative.

Field lines are not particle trajectories

A positive test charge released from rest initially accelerates along the local electric field. That does not mean its full path must coincide with a field line. Inertia carries the particle's velocity forward while the field direction can change.

The trajectory follows Newton's second law:

\[m\frac{d^2\mathbf r}{dt^2} =q_{\mathrm{test}}\mathbf E(\mathbf r)\]

A field line satisfies a first-order geometric equation, while a trajectory satisfies a second-order dynamical equation and depends on mass, charge sign, and initial velocity. A negative charge initially accelerates opposite the field-line arrows.

Equipotential contours provide an independent view

Electrostatic potential is a scalar field related to the electric field by

\[\mathbf E=-\boldsymbol{\nabla}V\]

An equipotential curve or surface has constant \(V\). The electric field is perpendicular to an equipotential wherever the gradient is nonzero and points toward decreasing potential.

Evenly spaced potential values produce contours that crowd where the potential changes rapidly, suggesting a larger field magnitude. This interpretation depends on the contour interval being constant and stated. Automatically chosen unequal levels can mislead.

Figure 1 overlays field directions and equipotentials for two separate point-charge examples. Follow any blue arrow: it crosses each dashed circle at a right angle. Reversing the charge reverses the arrow direction while preserving this geometry. The panels are independent examples, not two charges acting together as a dipole.

Nulls and singularities require different treatment

The charge disks in Figure 1 cover the singular source locations. They do not mark zero-field regions. Likewise, the equal lengths of the drawn spokes encode direction, not constant field strength along a spoke; the point-charge magnitude still decreases with distance. The schematic circle spacing does not represent equal potential steps.

A null point has a finite, well-defined field equal to zero because source contributions cancel. It should be displayed and labeled as a genuine result. A point-charge source location is a singularity where the ideal formula is undefined and its magnitude diverges. It should not be displayed as a zero-length arrow.

A singularity mask may omit points within a declared radius. Arrow clipping may keep the page readable near that mask. Both are presentation policies and must be recorded. If a finite-size source is intended, replace the point-source law with the physically appropriate charge distribution rather than hiding the singularity with an unexplained constant.

Streamline integration needs numerical checks

A field-line curve is found by numerical integration. A step that is too large can cut corners, pass through a source, or cross another computed line even though true field lines do not cross. Adaptive steps can shrink where the direction changes rapidly.

import numpy as np
import matplotlib.pyplot as plt

coordinates = np.linspace(-2, 2, 101)
x, y = np.meshgrid(coordinates, coordinates)
ex, ey = np.zeros_like(x), np.zeros_like(y)
mask = np.zeros_like(x, dtype=bool)
for source_x, charge in [(-0.7, 1e-9), (0.7, -1e-9)]:
    dx = x - source_x
    radius = np.hypot(dx, y)
    mask |= radius < 0.15
    safe_radius = np.maximum(radius, 0.15)
    ex += 8.9875517923e9 * charge * dx / safe_radius**3
    ey += 8.9875517923e9 * charge * y / safe_radius**3
fig, ax = plt.subplots()
ax.streamplot(x, y, np.ma.array(ex, mask=mask), np.ma.array(ey, mask=mask), density=1)
ax.set(xlabel="x (m)", ylabel="y (m)")
ax.set_aspect("equal")
plt.show()

Integrating forward and backward from each seed traces both directions, but arrowheads must still show the physical field direction. Repeat with a smaller step and compare curves at matching locations. A prettier curve is not proof of numerical convergence.

Color should not carry the only meaning

Color can encode magnitude, potential, or sign, but the legend must name the quantity, units, range, and scale. A diverging palette is useful for signed potential; field magnitude is nonnegative and usually needs a sequential palette.

Color choices should remain readable for common color-vision differences and in grayscale. Direction needs arrows or streamlines, not hue alone. Exact selected values and source descriptions should remain available as text so the physical result is not locked inside an image.

Verification before presentation

Use known fields before attempting a complicated source arrangement. One positive point charge should produce radial outward directions and inverse-square magnitudes. One negative charge should reverse every direction. Equal positive charges should cancel at their midpoint, while an equal positive-negative pair should have a nonzero midpoint field.

Keep a fixed probe and vary arrow scale, cap, color map, grid spacing, and streamline seed policy. None of those changes may alter its numerical components. Compare a field calculated directly from sources with the negative finite-difference gradient of potential away from sources, and reduce the difference spacing to test convergence.

A complete diagram reports the source configuration, coordinate axes, plane or volume, units, sampling resolution, magnitude encoding, clipping, singularity policy, and streamline seed rule. Those details turn an illustration into a reproducible scientific representation.

A worked Python notebook

Compare arrow magnitudes along a radial line from a positive point charge. The question for this calculation is precise: how does field magnitude change when we change radial distance, while keeping the other choices fixed? The earlier sections explain the physical relationship. Here we turn one part of that relationship into a calculation that you can run, inspect, and change in Google Colab.

Plot scaling must be disclosed; equal-length arrows can show direction but hide magnitude changes. Keep that sentence beside the results. A formula can return a number outside its useful range, and a plotting library will usually draw that number without asking whether the physical assumptions still hold. The selected interval is from 0.2 to 3 m. It gives us a specific domain to discuss instead of leaving the graph's range to a software default.

Use the notebook link above the lesson, run the setup cell, and then run the cells in order. The code below is also included there. NumPy handles the arrays of numerical values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these libraries or notebook cells are unfamiliar, start with Your first physics notebook.

State the relationship before choosing a graph

In this small example, q stands for radial distance, expressed in m. The output is field magnitude, expressed in N/C. The equation below uses the numerical values in those units. Any fixed coefficients therefore carry the units needed to make the relation consistent. A value supplied in another unit must be converted before it enters this expression.

\[f(q) = \frac{8.9875517923}{q^{2}}\]

This is a function of one changing input. It is not a statement that the physical system has only one variable. We deliberately hold the other inputs fixed so that one cause of variation is visible. Changing several inputs at once would make it harder to tell which change produced the output difference. Write down the held-fixed choices before trying a different experiment.

At 1 m, the expression gives 8.98755 N/C. This is our reference calculation. It is a prediction of the stated example, not a new measurement. Its displayed digits help us compare implementations. They should not be read as a claim that physical inputs are known to six significant figures.

import numpy as np
import sympy as sp
import matplotlib.pyplot as plt

q = sp.Symbol("q", real=True)
expression = sp.sympify("8.9875517923/q**2", locals={"q": q})
reference_input = 1.0
reference_output = float(expression.subs(q, reference_input))
print("Input:", reference_input, "m")
print("Predicted field magnitude:", reference_output, "N/C")

sp.Symbol declares a mathematical symbol. It does not assign a numerical measurement to that symbol. subs then replaces the symbol with our chosen input, and float converts the resulting symbolic number into a standard Python numerical value. Keeping these steps separate lets us inspect the equation before numerical substitution. It also prevents a later plot from becoming the only surviving record of the model.

Compare a few cases you can explain

Before drawing hundreds of points, calculate three. The lower endpoint gives 224.689 N/C. The midpoint, at 1.6 m, gives 3.51076 N/C. The upper endpoint gives 0.998617 N/C. Read these together with the assumptions: they describe different choices of radial distance within the same example, with the other inputs held fixed.

These three values are a useful first check, but they do not establish the shape between them. Two endpoints can be equal even when the curve bends or oscillates in between. Likewise, a large change between endpoints does not tell us whether the relationship is linear. We need the equation and intermediate samples to answer those questions.

evaluate = sp.lambdify(q, expression, modules="numpy")
inputs = np.array([0.2, 1.6, 3.0])
outputs = np.asarray(evaluate(inputs), dtype=float)
outputs = np.broadcast_to(outputs, inputs.shape)
for input_value, output_value in zip(inputs, outputs):
    print(f"{input_value:.6g} m -> {output_value:.6g} N/C")
assert np.all(np.isfinite(outputs))

lambdify turns the symbolic expression into a numerical function. We explicitly select NumPy as its numerical backend so it can accept an array. The same expression now has two useful forms: one for algebra and one for calculating many cases. The assertion checks that the chosen inputs produce finite outputs. It would catch an infinity or an undefined numerical result, but a finite value can still be physically inappropriate.

Make a graph that answers the question

The horizontal axis shows radial distance; the vertical axis shows field magnitude. Every plotted point is a prediction of the same expression. We mark the reference case separately so that a reader can connect the earlier printed value to its place on the curve. The axis labels include units because a shape without a scale cannot tell us the size of a physical effect.

input_grid = np.linspace(0.2, 3.0, 301)
output_grid = np.asarray(evaluate(input_grid), dtype=float)
output_grid = np.broadcast_to(output_grid, input_grid.shape)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(input_grid, output_grid, label="Stated model")
ax.scatter([reference_input], [reference_output], label="Reference case", zorder=3)
ax.set_xlabel("Radial distance (m)")
ax.set_ylabel("Field magnitude (N/C)")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()

Look for a sign change, a turning point, or a region where the curve becomes steep. Connect each feature to the expression rather than to the colour of the line. If the curve has a minimum or maximum, changing the input in opposite directions may have similar effects on the output near that point. If it is nearly straight over a short interval, a local linear approximation may be useful even when the complete expression is nonlinear.

Increasing the number of samples makes the line smoother and may reveal features that a coarse grid missed. It does not improve the physical inputs or enlarge the model's validity range. For quantities that can take only discrete values, use the line as a guide to the relationship and interpret only the allowed input values. A plotting function does not enforce such restrictions for you.

Measure the local sensitivity

A derivative asks a more specific question than the whole graph: how quickly does field magnitude change near the reference input? Its units are the output unit divided by the input unit. For this calculation, the derivative at 1 m is -17.9751 in those ratio units. Locally, the output decreases as the input increases. This statement is local; the sign or size of the slope can be different elsewhere on the curve.

\[f'(q) = - \frac{17.9751035846}{q^{3}}\]

For a small input change, multiply the derivative by that change to estimate the output change. Then compare that estimate with a fresh evaluation of the full expression. The distinction between these two calculations matters: the derivative gives a tangent approximation, while substitution evaluates the chosen expression at the new point.

slope_expression = sp.diff(expression, q)
slope_at_reference = float(slope_expression.subs(q, reference_input))
changed_input = 1.014
linear_prediction = reference_output + slope_at_reference * (
    changed_input - reference_input
)
full_prediction = float(evaluate(changed_input))
print("Symbolic derivative:", slope_expression)
print("Tangent prediction:", linear_prediction, "N/C")
print("Full expression:", full_prediction, "N/C")
print("Approximation difference:", full_prediction - linear_prediction, "N/C")

Here the changed input is 1.014 m. The tangent estimate is 8.7359 N/C, while the full expression gives 8.74109 N/C. If the two values are close, it means the chosen input change is small enough for this local approximation at this point. It does not mean the entire model is linear. If the slope is zero, a quadratic or higher-order term may supply the leading change instead.

This is also the beginning of uncertainty propagation. If the input has a small stated standard uncertainty, the magnitude of the slope times that uncertainty estimates one contribution to output uncertainty. Do not automatically use the same rule for a wide interval, a discontinuity, a turning point with zero first derivative, or several correlated uncertain inputs. Those situations need more of the model than one slope.

Check the derivative with numerical differences

We can estimate the same slope from values on either side of the reference point. Subtract the lower output from the upper output and divide by twice the input step. Parentheses are essential: the entire output difference must be divided by the entire input interval. Without them, Python can execute a different mathematical expression while still producing a plausible number.

The calculation below uses three decreasing step sizes. Each estimate is compared with the symbolic derivative, so the reference is independent of the numerical difference formula. Near an endpoint, it is acceptable here to evaluate a small extension only because the displayed mathematical expression is smooth there; such a check does not assert that extrapolated values describe additional physical cases.

input_span = 2.8
for fraction in [1e-2, 1e-3, 1e-4]:
    step = input_span * fraction
    upper = float(evaluate(reference_input + step))
    lower = float(evaluate(reference_input - step))
    numerical_slope = (upper - lower) / (2 * step)
    difference = numerical_slope - slope_at_reference
    print(f"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}")

For a smooth function, reducing the step often reduces the approximation error at first. Very small steps can eventually make subtraction of nearly equal floating-point values less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare the observed behaviour over a useful range of steps instead of choosing the smallest number the computer can represent.

An absolute slope difference is useful when the expected slope is near zero. A relative difference would divide by a very small reference and could look enormous even when the absolute discrepancy is tiny. Away from zero, a relative difference can help compare quantities with very different scales. The tolerance should reflect the question and the numerical method, rather than a universal decimal threshold copied into every test.

Change the example and preserve the reasoning

Make one copy of the reference calculation before editing it. Choose a second value of radial distance inside the stated interval, predict whether field magnitude will rise or fall, and then evaluate the expression. Place the prediction and the result in a text cell. If they disagree, identify whether the mistake was in the sign, the unit conversion, the algebra, or the assumption about how the curve behaves.

Next choose a shorter plotting interval around the reference point. Compare the local curve with its tangent approximation. Then widen the interval again. The difference shows why a useful local estimate need not describe the whole range. Keep the axis labels and numerical scale visible when comparing the plots; automatic axis limits can make two different effects appear equally large.

Finally, return to the physical limit stated at the start: Plot scaling must be disclosed; equal-length arrows can show direction but hide magnitude changes. Describe one change to the setup that would violate that limit. State what new input, equation, or observation would be needed before trusting an answer in the changed situation. This last step connects the Python experiment to the physics instead of treating successful execution as the only criterion for a useful result.

Before saving, restart the runtime and run all cells in order. A result that depends on an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep unrounded values for later calculations, round only the reported output, and label any new data as measured, assumed, or generated. The graph and printed values should remain traceable to the same expression and the same choices of inputs.

Recover the output change by integrating the slope

There is another way to check that the expression and its derivative describe the same relationship. Add up the small output changes predicted by the slope across the chosen input interval. In the continuous limit, this integral equals the output at the upper endpoint minus the output at the lower endpoint. The result has units of N/C: the input unit in the integration cancels the input unit in the denominator of the slope.

This statement is about the mathematics of this particular relationship. It does not assign a new physical meaning to an arbitrary area under a graph. For example, an area under force versus distance represents work, while an area under a different pair of quantities may represent something else or have no standard name. Always carry the axis units through the calculation before naming an integral.

slope_function = sp.lambdify(q, slope_expression, modules="numpy")
endpoint_change = float(evaluate(3.0) - evaluate(0.2))
for points in [101, 201, 401]:
    grid = np.linspace(0.2, 3.0, points)
    slopes = np.asarray(slope_function(grid), dtype=float)
    slopes = np.broadcast_to(slopes, grid.shape)
    integrated_change = np.trapezoid(slopes, grid)
    print(
        points,
        "integrated change:",
        integrated_change,
        "endpoint change:",
        endpoint_change,
    )

The trapezoidal rule joins neighbouring slope samples with straight segments and adds their signed areas. A negative contribution remains negative; replacing every slope by its magnitude would calculate a different quantity. Increasing the sample count provides a practical refinement check. If the values do not settle toward the endpoint difference, first inspect the interval, singularities, and array ordering.

Do not conclude that two agreeing calculations prove the model is physically complete. Both use the same selected relationship, so an omitted effect would be omitted from both. Their agreement is evidence that the numerical tools implement that relationship consistently. Comparing with an independent experiment or a more appropriate physical model is a separate test.

Keep this comparison in the notebook when you change the expression. It is particularly useful after adding a coefficient, changing a sign convention, or converting an input unit. A code cell that produces a smooth graph can conceal these mistakes; a second calculation of the same output change gives you another place to notice them.

Sources


Share to: