简体   繁体   English

用于使用matplotlib.pyplot在python中进行绘图的线型功能

[英]linestyle feature for plotting in python with matplotlib.pyplot

I'm trying to scatter or plot 2 sets of arrays using numpy and matplotlib. 我正在尝试使用numpy和matplotlib分散或绘制2组数组。 Everything is ok with the code except when I try to have lines instead of dots in my plot The plot is ok when I use : 使用代码一切正常,但当我尝试在情节中使用线条而不是圆点时,使用以下内容就可以了:

from numpy import *
import matplotlib.pyplot as plt
positions=open('test.txt','r')

lines=positions.readlines()

for i in range(0,len(lines)):
    line=lines[i] 
    values=line.split("     ")

    x_val = [float(values[0])]
    y_val = [float(values[1])]
   # plt.scatter(x_val,y_val)
    #Or
    plt.plot(x_val,y_val,'ro')
    plt.title(' Data')
    plt.xlabel('x ')
    plt.ylabel('y')
    plt.show()

positions.close()

在此处输入图片说明

But when I replace plt.plot(x_val,y_val,'ro') with plt.plot(x_val,y_val,'r') , or plt.plot(x_val,y_val,'-') What I get is merely a blank page! 但是当我用plt.plot(x_val,y_val,'r')plt.plot(x_val,y_val,'-')替换plt.plot(x_val,y_val,'ro')时我得到的仅仅是一个空白页! 在此处输入图片说明 I have no idea what the problem is, because I tried it with many many different options and yet the only option which works properly is having 'o'. 我不知道问题出在哪里,因为我尝试了许多不同的选项,但是唯一可以正常工作的选项是“ o”。

The reason that you see no lines when you ask for a plot without setting the markers is because you are plotting each (x,y) point individually, which can have a point position, but would create a line of length zero. 在不设置标记的情况下请求绘图时看不到线的原因是因为您正在分别绘制每个(x,y)点,这些点可以具有点位置,但会创建长度为零的线。

If instead of plotting each point immediately upon reading it, you put those values into an array, and called the plot function just once, you could also show a line: 如果不是在读取时立即绘制每个点,而是将这些值放入一个数组中,并且只调用了一次plot函数,那么还可以显示一条线:

x_vals = []
y_vals = []

for i in range(0,len(lines)):
    line=lines[i] 
    values=line.split("     ")

    x_vals.append(float(values[0]))
    y_vals.append(float(values[1]))

plt.plot(x_vals, y_vals,'ro-')

And you could still use the data in a scatter plot if required. 如果需要,您仍然可以在散点图中使用数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM