Этот рабочий код и его выходной график демонстрируют, как вы можете достичь того, что вам нужно. См. Комментарии в коде для более подробной информации.
import geopandas as gpd
from shapely.geometry import Point, LineString
import matplotlib.pyplot as plt
# handle all points and create relating lines
pA1 = Point(1.5, 1.75)
pA2 = Point(2, 2)
line_A = LineString([[pA1.x, pA1.y], [pA2.x, pA2.y]])
pB1 = Point(3.0, 2.0)
pB2 = Point(3, 4)
line_B = LineString([[pB1.x, pB1.y], [pB2.x, pB2.y]])
pC1 = Point(2.5, 1.25)
pC2 = Point(1, 1)
line_C = LineString([[pC1.x, pC1.y], [pC2.x, pC2.y]])
# create a geodataframe,
# assigning the column containing `LineString` as its geometry
pts_and_lines = gpd.GeoDataFrame([['A', pA1, pA2, 16, line_A],
['B', pB1, pB2, 18, line_B],
['C', pC1, pC2, 19, line_C]],
columns=['id', 'beg_pt', 'end_pt', 'value', 'LineString_obj'],
geometry='LineString_obj') # declare LineString (last column) as the `geometry`
# make a plot of the geodataframe obtained
f, ax = plt.subplots(1, figsize = [4, 4])
pts_and_lines.plot(ax=ax, column = 'value');
plt.show()
Выходной участок:
![enter image description here](https://i.stack.imgur.com/U1S2b.png)
Если вы предпочитаете сначала построить кадр данных, содержащий from_point
и to_point
, то добавьте новый столбец, содержащий LineString
, создавая из существующих точек, вот альтернативный код.
import geopandas as gpd
from shapely.geometry import Point, LineString
import matplotlib.pyplot as plt
# this dataframe `points_df` contains from_point, to_point for creating `lineString`.
points_df = gpd.GeoDataFrame([['A', Point(1.5, 1.75), Point(2, 2), 16],
['B', Point(3.0,2.0), Point(3, 4), 18],
['C', Point(2.5,1.25), Point(1, 1), 19]],
columns=['id', 'geometry_a', 'geometry_b', 'value'])
# add new column, `line` to the dataframe,
# this column contains `LineString` geometry.
points_df['line'] = points_df.apply(lambda x: LineString([x['geometry_a'], x['geometry_b']]), axis=1)
# assign geometry to `points_df` using the column that has `LineString` geometry
# take the result as `target_gdf`
# `target_gdf` is now capable of plotting with matplotlib
target_gdf = gpd.GeoDataFrame(points_df, geometry=points_df['line'])
f, ax = plt.subplots(1, figsize = [4, 4])
target_gdf.plot(ax=ax, column = 'value');
plt.show()
Выходной график такой же, как и у предыдущего.