用 pandas 绘制一维多线图 [英] 1D multiple lines plot with pandas
问题描述
我有一个包含 x1 和 x2 列的数据框.我想将每一行绘制为一维线,其中 x1 是起点,x2 是终点.下面我有我的解决方案,它不是很酷.此外,在同一图中绘制 900 条线时速度很慢.
I have a dataframe with x1 and x2 columns. I want to plot each row as an unidimensional line where x1 is the start and x2 is the end. Follows I have my solution which is not very cool. Besides it is slow when plotting 900 lines in the same plot.
创建一些示例数据:
import numpy as np
import pandas as pd
df_lines = pd.DataFrame({'x1': np.linspace(1,50,50)*2, 'x2': np.linspace(1,50,50)*2+1})
我的解决方案:
import matplotlib.pyplot as plt
def plot(dataframe):
plt.figure()
for item in dataframe.iterrows():
x1 = int(item[1]['x1'])
x2 = int(item[1]['x2'])
plt.hlines(0,x1,x2)
plot(df_lines)
它确实有效,但我认为它可以改进.提前致谢.
It actually works but I think it could be improved. Thanks in advance.
推荐答案
Matplotlib 可以节省大量绘制线条的时间,当它们以 LineCollection
进行组织时.不是像其他答案那样绘制 50 个单独的 hlines
,而是创建一个对象.
Matplotlib can save a lot of time drawing lines, when they are organized in a LineCollection
. Instead of drawing 50 individual hlines
, like the other answers do, you create one single object.
这样的 LineCollection
需要一个线顶点数组作为输入,它的形状需要 (行数,每行点数,2)
.所以在这种情况下 (50,2,2)
.
Such a LineCollection
requires an array of the line vertices as input, it needs to be of shape (number of lines, points per line, 2)
. So in this case (50,2,2)
.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
df_lines = pd.DataFrame({'x1': np.linspace(1,50,50)*2,
'x2': np.linspace(1,50,50)*2+1})
segs = np.zeros((len(df_lines), 2,2))
segs[:,:,0] = df_lines[["x1","x2"]].values
fig, ax = plt.subplots()
line_segments = LineCollection(segs)
ax.add_collection(line_segments)
ax.set_xlim(0,102)
ax.set_ylim(-1,1)
plt.show()
这篇关于用 pandas 绘制一维多线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!