如何从具有两个几何列的数据框中绘制表示值的线?

时间:2019-04-03 13:43:23

标签: python-3.x matplotlib geopandas

我有以下数据:

project

第一个几何列代表起点,第二个几何终点代表具有对应于value列的值的线。

我试图用以下方式绘制此图

get_object()

但是,它只是绘制第一列几何图形并为与它们的值相对应的点着色。

我如何生成一个绘制线条的图,以颜色对其值进行颜色编码?

1 个答案:

答案 0 :(得分:0)

此工作代码及其输出图解说明了如何实现所需的功能。有关更多详细信息,请参见代码中的注释。

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

如果您希望先构建包含from_pointto_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()

其输出图与上一个相同。