如何消除单图中多组折线/散点图间的不必要跨组连线?
如何消除单图中多组折线/散点图间的不必要跨组连线?
嘿,这个问题我太熟悉了!先帮你捋清楚问题根源:你现在的phi_N_bh和phi_M_bh2列表是定义在所有循环外面的,每次切换total_steel_area的时候,新计算出来的点都会追加到这两个列表的末尾,没有清空之前组的数据。这样当你调用ax.plot()时,Matplotlib会把所有累积的点从头到尾连起来,自然就出现了上一组最后一个点和下一组第一个点的多余连线。
解决办法超简单:把数据列表移到外层循环内部
每次进入新的total_steel_area循环时,重新创建空列表来存储当前组的x、y数据,这样每组数据都是完全独立的,不会和其他组的点混在一起。
修改后的代码如下(我标了关键修改的地方):
fig, ax = plt.subplots(dpi=100, figsize=(8,4)) # 把这两个列表的定义移到外层循环里! for total_steel_area in np.arange(0.01,0.06,0.01): phi_N_bh = [] # 每次循环都重置为空,只存当前组的点 phi_M_bh2 = [] # 每次循环都重置为空,只存当前组的点 for phi_x__h in np.arange(0.1,2,0.1): phi_N__bh, phi_M__bh2 = calculate_phi_N__bh_and_phi_M__bh2(phi_x__h, lamb, alpha_cc, eta, f_ck, E_s, varepsilon_cu2, phi_d__h, phi_d2__h, f_yk, total_steel_area/2, total_steel_area/2) phi_N_bh.append(phi_N__bh) phi_M_bh2.append(phi_M__bh2) ax.plot(phi_M_bh2, phi_N_bh, c='b') ax.scatter(phi_M_bh2, phi_N_bh, c='b', s=10) ax.set_title('Column Design Chart for Rectangular Column with Symmetrical Compression and Tension Reinforcement') ax.set_xlabel('M/bh²') ax.set_ylabel('N/bh') ax.text(1-0.1, 1-0.1, f'f_ck = {f_ck}, f_yk = {f_yk}', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) ax.text(1-0.1, 1-0.2, f'd/h = {phi_d__h}, d2/h = {phi_d2__h}', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes) ax.set_ylim(0) ax.set_xlim(0) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.legend()
这样修改之后,每个total_steel_area对应的折线只会连接当前组内的点,跨组的多余连线就会消失啦~

备注:内容来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

