matplotlib 带矩阵输入的Python散点图,在获取x轴上显示的列数时遇到问题,然后为每列中的每个值指定一个点

64jmpszr  于 2022-11-30  发布在  Python
关注(0)|答案(1)|浏览(117)

我正在制作一个 * 条形图 * 和一个 * 散点图 *。条形图以矢量作为输入。我在x轴上绘制了值,在y轴上绘制了它们重复的次数。这是通过将矢量转换为列表并使用.count()来完成的。这工作得很好,而且相对简单。
至于 * 散点图 *,输入是任意x和y维的矩阵。其思想是根据插入矩阵的列数,在x轴上显示矩阵中的列数,从1、2、3、4等。每列的行将由许多不同的数字组成,我希望所有这些数字都显示为相关列索引上方的点或星。例如,列#3由向下的值6、2、8、5、9、5组成,并且希望在x轴上的数字3的顶部直接为每个值在y轴上向上的点。我尝试了不同的方法,一些方法显示了点,但在错误的位置,其他时候,x轴是完全偏离,即使我使用.len(0,:),打印出正确的列数,但没有图表。I don“我连点和星都不显示:

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)

上面给出的矩阵只是我为了测试而做的一个,这个想法是它应该对任何导入的给定矩阵都有效。
我尝试了上面粘贴的代码,这是我所得到的最接近的,因为它实际上打印了它所拥有的列的数量,但它并没有在绘图上显示它们。我还没有得到一个点,它实际上在y轴上的列以上的点绘图,只有在完全错误的位置在以前的版本。

klsxnrf1

klsxnrf11#

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]])

rows, columns = vector.shape
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,columns]) # Set the limits of the x-axis
plt.ylim([-5,15]) # Set the limits of the y-axis

for i in range(1, columns+1):
    y = vector[:,i-1]
    x = [i] * rows
    plt.plot(x, y, "r.")

plt.show()

相关问题