如何连接点以绘制线段并且还形成平行线w.r.t.线段?

时间:2017-12-12 10:33:08

标签: python-3.x pandas csv matplotlib

我想绘制一条线段,该线段穿过我的图形的所有端点(曲线的最大值),该线段是从csv文件绘制的。对于该线段,我还需要通过在曲线上取一个点(已知)作为参考来绘制与该线段平行的线。

z,  x,  y
-40,0,0
-40,0.658,26.443
-40,1.316,47.128
-40,1.974,62.084
-40,2.632,73.336
-40,3.29,81.785
-40,3.948,87.501
-40,4.606,90.795
-40,5.264,92.491
-40,5.922,93.231
-40,6.58,93.41 - maximum value i.e end point of the curve
23,0,0
23,0.889,22.616
23,1.778,36.552
23,2.667,45.238
23,3.556,50.666
23,4.445,53.856
23,5.334,55.673
23,6.223,56.672
23,7.112,57.203
23,8.001,57.443
23,8.89,57.51- maximum value i.e end point of the curve
40,0,0
40,0.937,19.191
40,1.874,30.893
40,2.811,38.58
40,3.748,43.547
40,4.685,46.518
40,5.622,48.238
40,6.559,49.193
40,7.496,49.694
40,8.433,49.935
40,9.37,50.02- maximum value i.e end point of the curve

以上是我需要绘制的CSV文件,并且终点是mentioined。我需要使用Pandas函数将所有端点与行as in the image连接起来,我尝试使用以下代码执行此操作。例如,平行线在任何曲线w.r.t上取一个点。这一点是要绘制的线,应该与第一条线平行。

import csv
from tkinter import filedialog
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style
from mpldatacursor import datacursor

x=[]   # Initializing empty lists to store the 3 columns in csv
y=[]
z=[]
df = pd.DataFrame({'A' : []})

def readCSV(e):
        global df
        filename = filedialog.askopenfilename()
        df = pd.read_csv(filename, error_bad_lines=False)   #Reading CSV file using pandas
        read = csv.reader(df, delimiter = ",")
        fig = plt.figure()
        data_list = []
        ax= fig.add_subplot(111)
        df.set_index('x', inplace=True)  #Setting index
        df.groupby('z')['y'].plot(legend=True,ax=ax)   #grouping and plotting
        for line in ax.lines:
            xdata = line.get_xdata()
            ydata = line.get_ydata()
            s = line.append([6.58,8.89,9.37])
            r = line.append([93.41,57.51,50.02])
        ax.plot(s,r)
        ax.set_ylabel('y')
        ax.set_xlabel('x')
        ax.grid(True)
        plt.show()

1 个答案:

答案 0 :(得分:0)

要绘制连接图形端点的线,一种方法是获取每条线的最后一组坐标。这可以使用get_xdata()get_ydata()来完成。这将返回所有值,但我们只需要 last 值。这可以使用切片表示法[-1]

来完成
my_list = [1,2,3,4,5]
print (my_list[-1])
# 5

所以你的代码会变成:

s = []
r = []

df = pd.read_csv("test.csv", error_bad_lines=False)   #Reading CSV file using pandas

fig = plt.figure()
data_list = []
ax= fig.add_subplot(111)
df.set_index('x', inplace=True)  #Setting index
df.groupby('z')['y'].plot(legend=True,ax=ax)   #grouping and plotting

for line in ax.lines:
    s.append(line.get_xdata()[-1])
    r.append(line.get_ydata()[-1])

ax.plot(s, r, color="black", linestyle=":")
ax.set_ylabel('y')
ax.set_xlabel('x')
ax.grid(True)

plt.show()

给出了:

enter image description here