r/learnpython • u/Joltik2007 • 2h ago
Help with plotting annotations
I've been constructing a code to plot the atomic energy orbitals using matplotlib.pyplot. This is the actual plotting code.
levels = {f"{val.real:.3f}": float(round(val.real,3)) * -1 for val in sorted(eigenvalues)}
fig, ax = plt.subplots()
for i, (name, e) in enumerate(levels.items()):
ax.hlines(e, 0, 0.5, color="k", lw=2)
ax.text(0.5 + 0.35, e, name+' \u03B2', va="center")
for i in eigenvalues:
count = min(2, atoms)
atoms -= count
if count >= 1:
ax.annotate("", xy=(0.15, e+0.3),xytext=(0.15, e-0.2),arrowprops=dict(arrowstyle='simple', color = 'k'))
if count == 2:
ax.annotate("", xy=(0.35, e-0.3),xytext=(0.35, e+0.2),arrowprops=dict(arrowstyle='simple', color = 'k'))
ax.set_xlim(-0.5, len(levels))
ax.set_xticks([])
for side in ("top", "right", "bottom"):
ax.spines[side].set_visible(False)
ax.set_ylabel("Energy -->")
It's designed to construct this kind of graph when the variable atoms is =3
But what the code only seems to produce is when atoms =3
1
u/Embarrassed_You2272 1h ago
Two things going on, I ran your loop with the allyl case (3 atoms) to check.
for i in eigenvalues:loop runs once per level, so the first level you draw eats all the electrons: 2 arrows, then 1 more on top of them, then nothing left for the other levels.sorted(eigenvalues)goes from smallest eigenvalue up, but you plot-val, so the first level in your dict is actually the top line. That's why the arrows land up there.Drop the inner loop and walk the levels from lowest energy up, handing out 2 at a time:
With 3 electrons that gives a pair on the bottom level and one up arrow on the middle one, and 4 (butadiene) fills the bottom two.
One heads up for later: because the dict is keyed on the rounded value, degenerate levels (like the doubly degenerate ones in benzene) collapse into one key, so you'd only get 2 slots where there should be 4. If you go there, keep a list of energies instead of a dict.
1
u/ResidentPomegranate6 1h ago
assign first, then draw: occupied = [2] * (atoms // 2) plus one for an odd atom, zipped against the levels sorted by energy. as written the inner loop runs per level so the first level eats every electron.