如何用Matplotlib绘制目标样式散点图?Python新手代码调试求助
问题:无法绘制符合要求的散点图
我想要绘制图中所示的散点图,但我的代码似乎无法达到要求的效果。我是Python新手,没有太多相关经验。

原代码:
import matplotlib.pyplot as plt import pandas as pd import numpy as np Production_steps = [13,12,21,1,29,20,15,12,21,18,20,15,20,22,26,7,8,12,22,25,15,23,24,13,4,22,12] Step_name = ['Start','NA2S','waiting','NA+','vacume','NA-','90min_Wait','waiting','NA+','waiting','vacume','vacume','1h_wait','Pressue','vacume','vacume','NA+/-','NA+','Pressure','90min_Wait','Pressure','cool-','vacume','vacume','NA-','Pressure','Batch Start'] Parameter1 = [80,932,21,525,20,20,21,1090,19,60,18,33,19,936,1083,61,102,1088,935,38,20,83,21,79,1006,930,1088] # Create a DataFrame using the given data df = pd.DataFrame({'Production_steps': Production_steps, 'Step_name': Step_name, 'Parameter1': Parameter1}) # Get unique values of 'Step_name' unique_steps = df['Step_name'].unique() # Set up colors for each unique 'Step_name' colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_steps))) # Create a figure and axis fig, ax = plt.subplots(figsize=(13, 6)) # Loop through unique 'Step_name' values, filter data, and plot scatter points for i, step in enumerate(unique_steps): step_data = df[df['Step_name'] == step] ax.scatter(step_data['Production_steps'],step_data['Parameter1'], label=step, color=colors[i]) # Set labels and show legend ax.set_xlabel('Production_steps') ax.set_ylabel('Parameter1') # Create legend outside of plot to position it at the bottom fig.legend(loc='lower center', ncol=4, bbox_to_anchor=(0.5,-0.2)) # Show the scatter plot plt.show()
问题分析与修正
你的代码存在几个关键问题,导致无法匹配目标图效果:
- 缩进错误:
ax.set_xlabel行的缩进不正确,会直接导致代码运行报错。 - X轴逻辑错误:目标图的X轴是按数据顺序排列的序列点,但你用
Production_steps的数值作为X轴,导致相同数值的点重叠、顺序混乱。 - 图例布局问题:原图例位置超出画布范围,会导致部分内容被截断。
修正后的代码:
import matplotlib.pyplot as plt import pandas as pd import numpy as np Production_steps = [13,12,21,1,29,20,15,12,21,18,20,15,20,22,26,7,8,12,22,25,15,23,24,13,4,22,12] Step_name = ['Start','NA2S','waiting','NA+','vacume','NA-','90min_Wait','waiting','NA+','waiting','vacume','vacume','1h_wait','Pressue','vacume','vacume','NA+/-','NA+','Pressure','90min_Wait','Pressure','cool-','vacume','vacume','NA-','Pressure','Batch Start'] Parameter1 = [80,932,21,525,20,20,21,1090,19,60,18,33,19,936,1083,61,102,1088,935,38,20,83,21,79,1006,930,1088] # 创建DataFrame,添加顺序索引作为X轴基准 df = pd.DataFrame({ 'sequence': range(len(Production_steps)), # 新增顺序索引,保证点按排列顺序展示 'Production_steps': Production_steps, 'Step_name': Step_name, 'Parameter1': Parameter1 }) # 获取唯一步骤名称 unique_steps = df['Step_name'].unique() # 为每个步骤分配对应颜色 colors = plt.cm.rainbow(np.linspace(0, 1, len(unique_steps))) # 创建画布与坐标轴 fig, ax = plt.subplots(figsize=(15, 7)) # 循环绘制每个步骤的散点 for i, step in enumerate(unique_steps): step_data = df[df['Step_name'] == step] ax.scatter(step_data['sequence'], step_data['Parameter1'], label=step, color=colors[i], s=100) # 设置坐标轴标签 ax.set_xlabel('Production_steps') ax.set_ylabel('Parameter1') # 将X轴刻度替换为Production_steps的数值,同时保持点的顺序 ax.set_xticks(df['sequence']) ax.set_xticklabels(df['Production_steps']) # 调整图例位置与布局,避免内容截断 fig.legend(loc='lower center', ncol=4, bbox_to_anchor=(0.5, -0.15)) plt.tight_layout() # 显示图表 plt.show()
关键修改说明
- 新增顺序索引:添加
sequence列作为X轴基准,确保每个点按数据原始顺序排列,和目标图一致。 - 修正缩进错误:调整
ax.set_xlabel的缩进,保证代码正常运行。 - 优化X轴刻度:用
set_xticks和set_xticklabels实现“按顺序排列、显示Production_steps数值”的效果。 - 调整布局:通过
tight_layout()自动适配画布空间,同时微调图例位置避免截断。 - 增大散点尺寸:用
s=100参数让散点更清晰,匹配目标图的视觉效果。
内容的提问来源于stack exchange,提问作者wasif ahmed
相关产品推荐
相关产品推荐

