You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib绘制两个HDF5文件:重叠图与绘图样式优化求助

Modified Matplotlib Script for Overlapping Band Plots

Here's the fully revised script that meets all your requirements, with detailed explanations of key changes below:

import h5py
import matplotlib.pyplot as plt
import warnings
import matplotlib

warnings.filterwarnings("ignore") # Ignore all warnings
ticklabels=[r'$\Gamma$','F','Q','Z',r'$\Gamma$']

# Define scaling factor for Y-axis data (adjust this value as needed)
SCALE_FACTOR = 1.5

# Set global plot parameters, including Times New Roman font
params = {
    'mathtext.default': 'regular',
    'axes.linewidth': 1.2,
    'axes.edgecolor': 'Black',
    'font.family': 'serif',
    'font.serif': ['Times New Roman'],
    'axes.labelsize': 12,
    'xtick.labelsize': 10,
    'ytick.labelsize': 10,
    'legend.fontsize': 10
}
plt.rcParams.update(params)

fig, ax = plt.subplots(figsize=(8, 6))

def plot_bands(file_path, linestyle, label_prefix):
    """Helper function to load and plot bands from an HDF5 file"""
    # Define distinct colors for first 3 bands
    band_colors = ['#FF3333', '#3366FF', '#33CC33']
    with h5py.File(file_path, 'r') as f:
        dist = f[u'distance']
        freq = f[u'frequency']
        
        for i in range(len(dist)):
            for nbnd in range(len(freq[i][0])):
                x = []
                y = []
                for j in range(len(dist[i])):
                    x.append(dist[i][j])
                    # Apply Y-axis scaling factor
                    y.append(freq[i][j][nbnd] * SCALE_FACTOR)
                
                # Set style based on band index and file
                if nbnd < 3:
                    color = band_colors[nbnd]
                    # Add label for legend
                    plot_label = f"{label_prefix} Band {nbnd+1}"
                else:
                    color = 'black'
                    plot_label = None  # Skip legend for extra bands
                
                ax.plot(x, y, c=color, lw=2.0, alpha=0.8, 
                        linestyle=linestyle, label=plot_label)

# Plot both case files
plot_bands('case1.hdf5', linestyle='-', label_prefix='Case 1')
plot_bands('case2.hdf5', linestyle='--', label_prefix='Case 2')

# Labels, axis limits and ticks
ax.set_ylabel(r'Frequency (THz)', fontsize=12)
ax.set_xlabel(r'Wave Vector (q)', fontsize=12)
# Get x limits from case1 (assuming both files have same k-path)
with h5py.File('case1.hdf5', 'r') as f:
    dist = f[u'distance']
    ax.set_xlim([dist[0][0], dist[-1][-1]])
    xticks = [dist[i][0] for i in range(len(dist))]
    xticks.append(dist[-1][-1])
ax.set_xticks(xticks)
ax.set_xticklabels(ticklabels)

# Add grid and legend
ax.grid(which='major', axis='x', c='green', lw=2.5, linestyle='--', alpha=0.8)
ax.legend(loc='upper right', frameon=False)

# Save plot
plt.savefig('overlapping_bands.pdf', bbox_inches='tight', dpi=300)
plt.show()

Key Changes Explained:

  • Dual File Plotting: Created a reusable plot_bands() function to avoid redundant code, calling it once for each case file to generate the overlapping plot.
  • Times New Roman Font: Added font family parameters to global rcParams, ensuring all text (labels, ticks, legend) uses the required font.
  • Legend Support: Added descriptive labels to the first 3 bands of each case, then enabled the legend to distinguish between datasets.
  • Y-Axis Scaling: Added a configurable SCALE_FACTOR variable that multiplies all frequency values before plotting—adjust this to your desired constant.
  • Curve Style Customization: Used distinct solid colors for Case 1's first 3 bands, while Case 2's corresponding bands use the same colors but with dashed lines. Extra bands remain black for both cases, with Case 2 using dashed lines for consistency.

内容的提问来源于stack exchange,提问作者astha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:27:57