Matplotlib相图绘制:非均匀间隔参数轴自定义问询
解决非均匀间隔参数的相图轴刻度问题
问题背景
需要为参数扫描实验绘制相图,实验参数如下:
vmax_values = [1, 3, 6, 9, 12, 15] cost_values = [0.001, 0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05]
其中cost为非均匀间隔参数,当前代码生成的散点图因cost数值集中在小范围,导致数据点聚集在轴的一侧,需要自定义轴刻度,让每个参数组合的点均匀分布,制作参考用相图。
解决方案核心
采用分类轴绘制思路:直接用参数的索引作为绘图坐标(确保每个点在轴上均匀分布),再将轴刻度标签替换为对应的实际参数值,完全脱离数值大小对刻度位置的影响。
修改后的完整代码
import json import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import numpy as np json_file_path = 'D:/cost_pc/output/results.json' with open(json_file_path, 'r') as json_file: results_dict = json.load(json_file) cmap = ListedColormap(['green', 'cyan', 'red']) vmax_values = [1, 3, 6, 9, 12, 15] cost_values = [0.001, 0.0025, 0.005, 0.0075, 0.01, 0.025, 0.05] desired_replicate_number = 4 vmax_list, cost_list, result_list = [], [], [] # 用参数的索引作为分类坐标,确保均匀分布 vmax_categorical = np.arange(len(vmax_values)) cost_categorical = np.arange(len(cost_values)) for i, vmax in enumerate(vmax_values): for j, cost in enumerate(cost_values): vmax_list.append(vmax_categorical[i]) cost_list.append(cost_categorical[j]) # 获取指定重复次数的实验结果 result = results_dict.get(f"p_vmax_{vmax}_cost_{cost}", {}).get(str(desired_replicate_number), None) if result == "Cheater victory": result_list.append(1) # 作弊者获胜 elif result == "Broadcaster victory": result_list.append(2) # 广播者获胜 elif result == "Coexistence": result_list.append(0) # 共存 else: result_list.append(-1) plt.figure(figsize=(10, 6)) scatter = plt.scatter(cost_list, vmax_list, c=result_list, cmap=cmap, s=150, marker='o', edgecolors='k') plt.xlabel('Cost', fontsize=16) plt.ylabel('Vmax', fontsize=16) plt.title(f'Phase Diagram (Replicate {desired_replicate_number})', fontsize=18) # 关键修改:用分类索引作为刻度位置,实际参数值作为标签 plt.xticks(cost_categorical, ['0.001', '0.0025', '0.005', '0.0075', '0.01', '0.025', '0.05'], rotation='vertical') plt.yticks(vmax_categorical, [str(v) for v in vmax_values]) legend_labels = ['Coexistence', 'Cheater Victory', 'Broadcaster Victory'] legend_handles = [plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=cmap(i), markersize=10) for i in range(len(legend_labels))] plt.legend(legend_handles, legend_labels, loc='upper right') plt.grid(False) plt.tight_layout() plt.show()
关键修改说明
- X轴修正:将
plt.xticks的第一个参数从cost_values改为cost_categorical(即参数的索引序列[0,1,2,3,4,5,6]),确保每个刻度位置均匀分布,标签保留实际的cost数值。 - Y轴修正:同理,将
plt.yticks的第一个参数从vmax_values改为vmax_categorical,匹配绘图时使用的分类坐标,避免刻度位置偏移。
这样修改后,所有参数组合的点会在相图上均匀排列,完全解决因参数非均匀间隔导致的点聚集问题,生成符合需求的参考相图。
内容的提问来源于stack exchange,提问作者Vijayraj Singh
相关产品推荐
相关产品推荐

