matplot lib中每个坐标的折线图

2024-09-30 08:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图画出连接起点(x,y)和终点(x,y)的线 这意味着一条线将连接(x1start,y1start)到(x1end,y1end) 数据框中有多行。 复制实际数据帧的示例数据帧如下所示:

df = pd.DataFrame()
df ['Xstart'] = [1,2,3,4,5]
df ['Xend'] = [6,8,9,10,12]
df ['Ystart'] = [0,1,2,3,4]
df ['Yend'] = [6,8,9,10,12]

据此,如果我们看df的第一行,一条线将连接(1,0)到(6,6) 为此,我使用For循环为每行绘制一条线,如下所示:

  fig,ax = plt.subplots()
fig.set_size_inches(7,5)

for i in range (len(df)):
    ax.plot((df.iloc[i]['Xstart'],df.iloc[i]['Xend']),(df.iloc[i]['Ystart'],df.iloc[i]['Yend']))
    ax.annotate("",xy = (df.iloc[i]['Xstart'],df.iloc[i]['Xend']),
    xycoords = 'data',
    xytext = (df.iloc[i]['Ystart'],df.iloc[i]['Yend']),
    textcoords = 'data',
    arrowprops = dict(arrowstyle = "->", connectionstyle = 'arc3', color = 'blue'))

plt.show()

我运行此程序时出现以下错误消息

我得到的数字如下所示:

enter image description here

箭头和线条按预期插入。箭头应该在每行的终点

有人能告诉我这是怎么回事吗

谢谢你

泽普


Tags: 数据dfdatafigplt箭头ax起点
3条回答

你把箭头的位置搞混了。xyxytext中的每个坐标对由x和y值组成

此外,为了查看绘图中的箭头,您需要手动设置绘图的限制,因为在缩放数据限制时,注释是不被考虑的

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame()
df ['Xstart'] = [1,2,3,4,5]
df ['Xend'] = [6,8,9,10,12]
df ['Ystart'] = [0,1,2,3,4]
df ['Yend'] = [6,8,9,10,12]


fig,ax = plt.subplots()
fig.set_size_inches(7,5)

for i in range (len(df)):
    ax.annotate("",xy = (df.iloc[i]['Xend'],df.iloc[i]['Yend']),
                xycoords = 'data',
                xytext = (df.iloc[i]['Xstart'],df.iloc[i]['Ystart']),
                textcoords = 'data',
                arrowprops = dict(arrowstyle = "->", 
                                  connectionstyle = 'arc3', color = 'blue'))

ax.set(xlim=(df[["Xstart","Xend"]].values.min(), df[["Xstart","Xend"]].values.max()),
       ylim=(df[["Ystart","Yend"]].values.min(), df[["Ystart","Yend"]].values.max()))
plt.show()

enter image description here

不是100%确定,但我认为在第二行中,您需要将xy=tuple后面的部分设置为,否则它会将前面的部分设置为关键字参数,并尝试将后面的部分作为普通参数传递

如果要绘制线段,请使用以下代码。您可能需要箭头或某种annotate元素(注意拼写是否正确),但您的目标似乎是绘制线段,这就完成了:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame()
df ['Xstart'] = [1,2,3,4,5]
df ['Xend'] = [6,8,9,10,12]
df ['Ystart'] = [0,1,2,3,4]
df ['Yend'] = [6,8,9,10,12]

fig = plt.figure()
ax = fig.add_subplot(111)
for i in range (len(df)):
    ax.plot(
        (df.iloc[i]['Xstart'],df.iloc[i]['Xend']),
        (df.iloc[i]['Ystart'],df.iloc[i]['Yend'])
    )
plt.show()

相关问题 更多 >

    热门问题