Would you like help checking which fonts are available on your system to avoid this in the future?
in region ylim(11, 16) the bands color are not seeing very differenct.now write code in which bands in the mention y axis region look as an above image
If the bands' colors look too similar or not distinguishable enough in the y-axis range (11 to 16), this is often because the number of lines (bands) is large and the colormap you use (viridis) produces somewhat smooth color gradients that may appear close.
How to improve color distinction:
Use a colormap with more contrast or qualitative colormaps designed for categorical data (like tab20, tab10, etc.).
Reduce the band colors to a distinct set cycling through a smaller palette.
Adjust the alpha (transparency) if needed.
Alternatively, highlight bands only in that region or with specific properties (e.g., those crossing the Fermi energy), but you asked for "bands in the mentioned region," so mainly colors matter.
Here is modified code with a qualitative colormap and distinct colors repeated (for up to 20 bands, which should be enough for clarity).
I also add a legend label for the bands to clarify that each colored line is a band (can be adjusted).
python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams
# Use a commonly available serif font
rcParams.update({
"font.family": "serif",
"font.serif": ["DejaVu Serif"],
"font.size": 12,
"axes.labelsize": 14,
"axes.titlesize": 16,
"xtick.labelsize": 12,
"ytick.labelsize": 12,
"legend.fontsize": 11,
"lines.linewidth": 1.8,
"axes.linewidth": 1.5,
"xtick.major.width": 1.2,
"ytick.major.width": 1.2,
"text.usetex": False,
"figure.dpi": 600,
"savefig.dpi": 600,
"figure.autolayout": True
})
# Load band data
try:
data = np.loadtxt('ti3in_bands.dat.gnu')
k = np.unique(data[:, 0])
bands = data[:, 1].reshape(-1, len(k))
except FileNotFoundError:
raise FileNotFoundError("Band structure data file 'ti3in_bands.dat.gnu' not found.")
# Fermi energy
fermi_energy = 13.7295
# High-symmetry points
sym_indices = [0, 40, 80, 120, 160, 200, 240, 280]
sym_points = [k[i] for i in sym_indices]
sym_labels = [r'Γ', 'M', 'K', r'Γ', 'A', 'L', 'H', 'A']
# Plot
fig, ax = plt.subplots(figsize=(8, 6))
# Use a qualitative colormap with high contrast colors
# 'tab20' has 20 distinct colors, cycle through if more bands
cmap = plt.get_cmap('tab20')
num_colors = cmap.N # 20 colors in tab20
for i, band in enumerate(bands):
color = cmap(i % num_colors)
band_clipped = np.clip(band, 11, 16)
ax.plot(k, band_clipped, color=color, alpha=0.9) # less transparency for more vivid colors
# Fermi level
ax.axhline(fermi_energy, linestyle='--', color='red', linewidth=1.5)
ax.text(k[0] + 0.02, fermi_energy + 0.15, r'$E_\mathrm{F}$', color='red', fontsize=12)
# Vertical lines for symmetry points, excluding first and last
for point in sym_points[1:-1]:
ax.axvline(point, color='gray', linestyle=':', linewidth=0.8)
ax.set_xticks(sym_points)
ax.set_xticklabels(sym_labels)
ax.set_xlabel("Wave Vector")
ax.set_ylabel("Energy (eV)")
ax.set_title(r"Electronic Band Structure of Ti$_3$In")
ax.set_ylim(11, 16)
ax.set_xlim(k[0], k[-1])
ax.grid(axis='y', linestyle=':', alpha=0.4)
plt.tight_layout()
plt.savefig('Ti3In_Bands_Colored.png', dpi=600)
plt.show()
Explanation:
Replaced the viridis colormap with the tab20 qualitative colormap which provides clearly distinguishable colors for categories (bands).
Set full alpha to 0.9 (less transparent) to get more vivid colors.
Cycled through colors if bands > 20 (can be adjusted to larger colormaps).
Clipped bands same way to y-limits (11 to 16).
This should make the bands in your energy region more visually distinct.
If you want, you can also add a legend with representative bands, or mark only some bands emphasized, but typically band structure plots don't include legends since bands are many and usually understood from context.
Let me know if you want to add such features!
Certainly! To highlight only the bands crossing the Fermi energy (13.7295 eV) within the plotting range (11 – 16 eV), we can:
Check which bands cross the Fermi level somewhere along k,
Plot all bands in a lighter color or low alpha (grayish),
Highlight the crossing bands with strong colors from the colormap,
Keep clipping the bands to the y-range [11, 16].
Here is the modified code with that behavior:
python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams
# Use a commonly available serif font
rcParams.update({
"font.family": "serif",
"font.serif": ["DejaVu Serif"],
"font.size": 12,
"axes.labelsize": 14,
"axes.titlesize": 16,
"xtick.labelsize": 12,
"ytick.labelsize": 12,
"legend.fontsize": 11,
"lines.linewidth": 1.8,
"axes.linewidth": 1.5,
"xtick.major.width": 1.2,
"ytick.major.width": 1.2,
"text.usetex": False,
"figure.dpi": 600,
"savefig.dpi": 600,
"figure.autolayout": True
})
# Load band data
try:
data = np.loadtxt('ti3in_bands.dat.gnu')
k = np.unique(data[:, 0])
bands = data[:, 1].reshape(-1, len(k))
except FileNotFoundError:
raise FileNotFoundError("Band structure data file 'ti3in_bands.dat.gnu' not found.")
# Fermi energy
fermi_energy = 13.7295
# High-symmetry points
sym_indices = [0, 40, 80, 120, 160, 200, 240, 280]
sym_points = [k[i] for i in sym_indices]
sym_labels = [r'Γ', 'M', 'K', r'Γ', 'A', 'L', 'H', 'A']
fig, ax = plt.subplots(figsize=(8, 6))
# Colormap for highlighted bands (crossing)
cmap = plt.get_cmap('tab20')
num_colors = cmap.N # 20 distinct colors
# Identify bands crossing the Fermi energy
crossing_bands_indices = []
for i, band in enumerate(bands):
# Check if band crosses Fermi energy: i.e.,
# minimum < E_F < maximum OR maximum < E_F < minimum (bands can be decreasing)
if np.min(band) <= fermi_energy <= np.max(band):
crossing_bands_indices.append(i)
# Plot all bands in light gray (background)
for i, band in enumerate(bands):
band_clipped = np.clip(band, 11, 16)
ax.plot(k, band_clipped, color='lightgray', alpha=0.5, linewidth=1)
# Plot crossing bands with distinct colors and stronger alpha
for idx_i, i in enumerate(crossing_bands_indices):
band = bands[i]
band_clipped = np.clip(band, 11, 16)
color = cmap(idx_i % num_colors)
ax.plot(k, band_clipped, color=color, alpha=0.9, linewidth=2.2, label=f'Band {i+1}')
# Fermi energy line
ax.axhline(fermi_energy, linestyle='--', color='red', linewidth=1.5)
ax.text(k[0] + 0.02, fermi_energy + 0.15, r'$E_\mathrm{F}$', color='red', fontsize=12)
# Vertical lines for symmetry points, excluding first and last
for point in sym_points[1:-1]:
ax.axvline(point, color='gray', linestyle=':', linewidth=0.8)
ax.set_xticks(sym_points)
ax.set_xticklabels(sym_labels)
ax.set_xlabel("Wave Vector")
ax.set_ylabel("Energy (eV)")
ax.set_title(r"Electronic Band Structure of Ti$_3$In")
ax.set_ylim(11, 16)
ax.set_xlim(k[0], k[-1])
ax.grid(axis='y', linestyle=':', alpha=0.4)
# Optional: Add legend for crossing bands (can become crowded if many bands cross)
if len(crossing_bands_indices) > 0:
ax.legend(loc='upper right', ncol=1, title="Bands crossing $E_F$", fontsize=9)
plt.tight_layout()
plt.savefig('Ti3In_Bands_HighlightCrossing.png', dpi=600)
plt.show()
What changed:
All bands first plotted in light gray, alpha 0.5, thinner.
Bands crossing Fermi energy are found by checking if Fermi level lies between their minimum and maximum energy.
Those crossing bands are plotted again on top with vibrant colors from tab20 (cycling if more than 20).
Crossing bands' linewidth increased for emphasis.
Added legend showing band indices of crossing bands — useful if not too many bands cross.
Rest of plot style preserved, including high-symmetry points and axis limits.
This will clearly highlight only the bands crossing Fermi energy in your energy window with visible contrasting colors, while other bands remain lightly visible in the background.
If you want the indices/labels or colors customized or an alternative approach, just ask!
To determine the bandgap from a band structure dataset you typically want to:
Identify the valence band maximum (VBM) — the highest occupied band energy below (or equal to) the Fermi energy.
Identify the conduction band minimum (CBM) — the lowest unoccupied band energy above the Fermi energy.
Calculate the bandgap = CBM - VBM.
If CBM ≤ VBM (or if they overlap), then the system is metallic (no band gap).
How to extract VBM, CBM from your data:
Since you have multiple bands and k-points, and the Fermi level (fermi_energy=13.7295 eV), here is a robust approach:
For each k-point (each column in bands array),
Find max band energy ≤ fermi_energy → candidate VBM at this k-point.
Find min band energy > fermi_energy → candidate CBM at this k-point.
Globally, find the max of all VBM candidates → VBM and k-point location.
Globally, find the min of all CBM candidates → CBM and k-point location.
Bandgap = CBM - VBM if CBM > VBM, else 0 or "metallic".
Incorporate this in your plotting code with printout and annotation:
python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams
# Use a commonly available serif font
rcParams.update({
"font.family": "serif",
"font.serif": ["DejaVu Serif"],
"font.size": 12,
"axes.labelsize": 14,
"axes.titlesize": 16,
"xtick.labelsize": 12,
"ytick.labelsize": 12,
"legend.fontsize": 11,
"lines.linewidth": 1.8,
"axes.linewidth": 1.5,
"xtick.major.width": 1.2,
"ytick.major.width": 1.2,
"text.usetex": False,
"figure.dpi": 600,
"savefig.dpi": 600,
"figure.autolayout": True
})
# Load band data
try:
data = np.loadtxt('ti3in_bands.dat.gnu')
k = np.unique(data[:, 0])
bands = data[:, 1].reshape(-1, len(k))
except FileNotFoundError:
raise FileNotFoundError("Band structure data file 'ti3in_bands.dat.gnu' not found.")
fermi_energy = 13.7295
sym_indices = [0, 40, 80, 120, 160, 200, 240, 280]
sym_points = [k[i] for i in sym_indices]
sym_labels = [r'Γ', 'M', 'K', r'Γ', 'A', 'L', 'H', 'A']
# Find VBM and CBM
# Initialize arrays for VBM and CBM per k-point
vbm_per_k = np.full(len(k), -np.inf)
cbm_per_k = np.full(len(k), np.inf)
for ki in range(len(k)):
energies_at_k = bands[:, ki]
vbm_candidates = energies_at_k[energies_at_k <= fermi_energy]
cbm_candidates = energies_at_k[energies_at_k > fermi_energy]
if vbm_candidates.size > 0:
vbm_per_k[ki] = np.max(vbm_candidates)
else:
vbm_per_k[ki] = -np.inf # No states below Fermi at this k-point
if cbm_candidates.size > 0:
cbm_per_k[ki] = np.min(cbm_candidates)
else:
cbm_per_k[ki] = np.inf # No states above Fermi at this k-point
# Global VBM and CBM
VBM = np.max(vbm_per_k)
VBM_k = k[np.argmax(vbm_per_k)]
CBM = np.min(cbm_per_k)
CBM_k = k[np.argmin(cbm_per_k)]
# Calculate bandgap
if CBM > VBM:
bandgap = CBM - VBM
else:
bandgap = 0 # Metallic or zero bandgap
print(f"Valence Band Maximum (VBM) = {VBM:.4f} eV at k = {VBM_k:.4f}")
print(f"Conduction Band Minimum (CBM) = {CBM:.4f} eV at k = {CBM_k:.4f}")
print(f"Bandgap = {bandgap:.4f} eV")
# Plotting
fig, ax = plt.subplots(figsize=(8, 6))
cmap = plt.get_cmap('tab20')
num_colors = cmap.N
# Identify bands crossing Fermi energy
crossing_bands_indices = []
for i, band in enumerate(bands):
if np.min(band) <= fermi_energy <= np.max(band):
crossing_bands_indices.append(i)
# Plot all bands light gray
for i, band in enumerate(bands):
band_clipped = np.clip(band, 11, 16)
ax.plot(k, band_clipped, color='lightgray', alpha=0.5, linewidth=1)
# Highlight crossing bands
for idx_i, i in enumerate(crossing_bands_indices):
band = bands[i]
band_clipped = np.clip(band, 11, 16)
color = cmap(idx_i % num_colors)
ax.plot(k, band_clipped, color=color, alpha=0.9, linewidth=2.2, label=f'Band {i+1}')
# Fermi level
ax.axhline(fermi_energy, linestyle='--', color='red', linewidth=1.5)
ax.text(k[0] + 0.02, fermi_energy + 0.15, r'$E_\mathrm{F}$', color='red', fontsize=12)
# Vertical symmetry lines
for point in sym_points[1:-1]:
ax.axvline(point, color='gray', linestyle=':', linewidth=0.8)
ax.set_xticks(sym_points)
ax.set_xticklabels(sym_labels)
ax.set_xlabel("Wave Vector")
ax.set_ylabel("Energy (eV)")
ax.set_title(r"Electronic Band Structure of Ti$_3$In")
ax.set_ylim(11, 16)
ax.set_xlim(k[0], k[-1])
ax.grid(axis='y', linestyle=':', alpha=0.4)
# Annotate bandgap info on the plot if nonzero
if bandgap > 0:
text_str = f"Bandgap = {bandgap:.3f} eV\nVBM at k={VBM_k:.3f}\nCBM at k={CBM_k:.3f}"
else:
text_str = "Metallic (no bandgap)"
ax.text(0.95, 0.05, text_str, transform=ax.transAxes,
fontsize=11, verticalalignment='bottom', horizontalalignment='right',
bbox=dict(boxstyle='round,pad=0.5', facecolor='white', alpha=0.8))
# Optional legend for crossing bands
if len(crossing_bands_indices) > 0:
ax.legend(loc='upper right', ncol=1, title="Bands crossing $E_F$", fontsize=9)
plt.tight_layout()
plt.savefig('Ti3In_Bands_Bandgap_Highlight.png', dpi=600)
plt.show()
What this does:
Prints in terminal the VBM, CBM, and bandgap values with k locations.
Annotates the bandgap info on the bottom right of the plot.
Plots bands as before with highlighted bands crossing Fermi energy.
Clearly shows Fermi energy and high-symmetry points.
Suitable for insulating/semiconducting and metallic cases.
If you want me to add support for an indirect bandgap detection (minimum CBM and maximum VBM possibly at different k-points — which is done above), this is it already.