Python矩阵散点图绘制问题:X轴列数与点位置异常
散点图绘制问题解决
我现在在做柱状图和散点图,柱状图用向量做输入,X轴放值,Y轴放重复次数,把向量转成列表用.count()实现,效果没问题。
但散点图卡壳了:输入是任意维度的矩阵,要求X轴显示列号(从1开始按列数递增),每列的所有行值作为点,对应显示在X轴对应列号的上方(比如第3列值是6、2、8、5、9、5,就要在X=3的位置上方显示这些点)。
试了好几种方法,有的能显示点但位置不对,有时候X轴直接乱了,虽然用len(vector[0,:])能正确输出列数,但图表里就是显示不对。最新写的代码连点都显示不出来:
import numpy as np # Import NumPy import matplotlib.pyplot as plt # Import the matplotlib.pyplot module vector = np.array([[-3,7,12,4,0o2,7,-3],[7,7,12,4,0o2,4,12],[12,-3,4,10,12,4,-3],[10,12,4,0o3,7,10,12]]) x = len(vector[0,:]) print(x)#vector[0,:] y = vector[:,0] plt.plot(x, y, "r.") # Scatter plot with blue stars plt.title("Scatter plot") # Set the title of the graph plt.xlabel("Column #") # Set the x-axis label plt.ylabel("Occurences of values for each column") # Set the y-axis label plt.xlim([1,len(vector[0,:])]) # Set the limits of the x-axis plt.ylim([-5,15]) # Set the limits of the y-axis plt.show(vector)
问题分析
你的代码有几个关键错误:
x = len(vector[0,:])只取了列数的数值(比如测试矩阵是7列,x就是7),不是每个点对应的X轴列号,导致所有点都被画在X=7的位置,加上xlim限制,自然看不到正确的点plt.show(vector)是错误用法,plt.show()不需要传任何参数- 只处理了第0列的数据,没有遍历所有列
修正后的代码
import numpy as np import matplotlib.pyplot as plt # 测试矩阵(可替换为任意维度矩阵) matrix = np.array([[-3,7,12,4,0o2,7,-3],[7,7,12,4,0o2,4,12],[12,-3,4,10,12,4,-3],[10,12,4,0o3,7,10,12]]) # 获取矩阵列数,用shape[1]比len更稳妥,兼容一维矩阵情况 num_cols = matrix.shape[1] # 遍历每一列,绘制对应列号的散点 for col_idx in range(num_cols): # 生成当前列所有点的X轴值:列号(从1开始),重复行数次数 x_vals = np.full(matrix.shape[0], col_idx + 1) # 获取当前列的所有Y轴值 y_vals = matrix[:, col_idx] # 绘制红色点 plt.plot(x_vals, y_vals, "r.") plt.title("Scatter plot") plt.xlabel("Column #") plt.ylabel("Values in each column") # 设置X轴刻度为实际列号,避免自动刻度偏移 plt.xticks(range(1, num_cols + 1)) # X轴左右留一点空间,避免点贴边 plt.xlim([0.5, num_cols + 0.5]) plt.ylim([-5, 15]) plt.show()
代码说明
- 用
matrix.shape[1]获取列数,比len(vector[0,:])更通用,即使输入是一维矩阵也能正常处理 - 遍历每一列,给该列所有点分配对应的X轴列号(从1开始)
- 用
np.full生成和行数相同的列号数组,保证每个点都对应正确的X位置 - 设置X轴刻度为实际列号,让图表显示更直观
内容的提问来源于stack exchange,提问作者35trokes
相关产品推荐
相关产品推荐

