温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么绘制矢量数据

发布时间:2021-07-02 16:11:48 来源:亿速云 阅读:324 作者:Leah 栏目:大数据

这期内容当中小编将会给大家带来有关Python中怎么绘制矢量数据,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

1 矢量数据绘制

学习目标:

  • 为多个矢量数据集绘制地图,并根据属性进行配色

  • 自定义地图图例

创建自定义地图

在本节中,将学习如何自定义地图符号和用于在Python中表示矢量数据的颜色和符号,使用geopandas和matplotlib进行地图绘制

首先导入需要使用到的包:

import os
import matplotlib.pyplot as plt
import numpy as np
from shapely.geometry import box
import geopandas as gpd
import earthpy as et
# 下载数据
# data = et.data.get_data('spatial-vector-lidar')
os.chdir(os.path.join(et.io.HOME, 'learning','python_data_plot'))
# 导入数据
sjer_roads_path="data/california/madera-county-roads/tl_2013_06039_roads.shp"
sjer_roads = gpd.read_file(sjer_roads_path)
print(type(sjer_roads['RTTYP']))
print(sjer_roads['RTTYP'].unique())
<class 'pandas.core.series.Series'>
['M' None 'S' 'C']

缺失值替换

可以看出道路类型中有一些缺失的值,由于需要绘制所有的道路类型,甚至那些设置为None的道路类型,下面将RTTYP属性NoneUnknown

sjer_roads['RTTYP'].replace(np.nan,"Unknown",inplace=True)
# sjer_roads.loc[sjer_roads['RTTYP'].isnull(), 'RTTYP'] = 'Unknown'
print(sjer_roads['RTTYP'].unique())
['M' 'Unknown' 'S' 'C']

如果使用geopandas.Plot()绘制数据,当设置了column =参数后,则geopandas将为线条自动选择颜色,可以使用legend = True参数添加图例

fig, ax = plt.subplots(figsize=(14,6))

sjer_roads.plot(column='RTTYP',
                categorical=True,
                legend=True,
                ax=ax
               )

# 调整图例位置
leg = ax.get_legend()
leg.set_bbox_to_anchor((1.15,0.5))

# 隐藏边框
ax.set_axis_off()

plt.show()

Python中怎么绘制矢量数据

根据属性指定颜色

为了按属性值绘制一个矢量图层,这样每条道路图层就会根据它各自的属性值来着色,所以图例也代表了同样的符号,需要三个步骤:

  1. 创建一个将特定颜色与特定属性值关联的字典

  2. 循环遍历并将该颜色应用于每个属性值

  3. 最后,在绘图中添加一个label参数,以便调用ax.legend()生成最终的图例

下面,先创建一个字典来定义您希望使用哪种颜色绘制每种道路类型:

# Create a dictionary where you assign each attribute value to a particular color
roadPalette = {'M': 'blue',
               'S': 'green',
               'C': 'purple',
               'Unknown': 'grey'}
roadPalette
{'M': 'blue', 'S': 'green', 'C': 'purple', 'Unknown': 'grey'}

接下来,循环遍历每个属性值,并使用字典中指定的颜色用该属性值绘制线条

fig, ax = plt.subplots(figsize=(10,10))

# 根据道路类型分组进行绘制
for ctype,data in sjer_roads.groupby('RTTYP'):
    
    color = roadPalette[ctype]
    
    data.plot(color=color,
              ax=ax,
              label=ctype
             )

ax.legend(bbox_to_anchor=(1.0, .5), prop={'size': 12})
ax.set(title='Madera County Roads')

ax.set_axis_off()
plt.show()

Python中怎么绘制矢量数据

调整线条宽度

可以通过linewidth =属性对线条宽度进行设置,

fig, ax = plt.subplots(figsize=(10, 10))

# Loop through each group (unique attribute value) in the roads layer and assign it a color
for ctype, data in sjer_roads.groupby('RTTYP'):
    color = roadPalette[ctype]
    data.plot(color=color,
              ax=ax,
              label=ctype,
              linewidth=4)  # Make all lines thicker

# Add title and legend to plot
ax.legend()
ax.set(title='Madera County Roads')
ax.set_axis_off()

plt.show()

Python中怎么绘制矢量数据

根据属性调整线条宽度

与着色相同,先创建线条宽度与类型的映射关系,然后分组进行循环绘制

# Create dictionary to map each attribute value to a line width
lineWidths = {'M': 1, 'S': 1, 'C': 4, 'Unknown': .5}

# Plot data adjusting the linewidth attribute
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_axis_off()

for ctype, data in sjer_roads.groupby('RTTYP'):
    color = roadPalette[ctype]    
    data.plot(color=color,
              ax=ax,
              label=ctype,
              
              # Assign each group to a line width using the dictionary created above
              linewidth=lineWidths[ctype])

ax.legend()
ax.set(title='Madera County \n Line width varies by TYPE Attribute Value')
plt.show()

Python中怎么绘制矢量数据

自定义绘制图例

在上面的实验中,使用label=True显示图例,ax.legend()loc=参数可以对图例位置进行调整,ax.legend()的常用参数有:

  • loc=(how-far-right,how-far-above)

  • fontsize=,设置图例字体大小

  • frameon=,是否显示图例边框

lineWidths = {'M': 1, 'S': 2, 'C': 1.5, 'Unknown': 3}

fig, ax = plt.subplots(figsize=(10, 10))

# Loop through each attribute value and assign each 
# with the correct color & width specified in the dictionary
for ctype, data in sjer_roads.groupby('RTTYP'):
    color = roadPalette[ctype]
    label = ctype    
    data.plot(color=color,
              ax=ax,
              linewidth=lineWidths[ctype],
              label=label)


ax.set(title='Madera County \n Line width varies by TYPE Attribute Value')

# Place legend in the lower right hand corner of the plot
ax.legend(loc='lower right',
          fontsize=15,
          frameon=True)

ax.set_axis_off()
plt.show()

png

观察当将图例frameon属性设置为False并调整线宽时会发生什么情况,注意loc = ()参数被赋予一个元组,它定义了图例相对于绘图区域的xy的位置

lineWidths = {'M': 1, 'S': 2, 'C': 1.5, 'Unknown': 3}

fig, ax = plt.subplots(figsize=(10, 10))

for ctype, data in sjer_roads.groupby('RTTYP'):
    color = roadPalette[ctype]
    label = ctype
    data.plot(color=color,
              ax=ax,
              linewidth=lineWidths[ctype],
              label=label)

ax.set(title='Madera County \n Line width varies by TYPE Attribute Value')
ax.legend(loc=(1, 0.5),
          fontsize=15,
          frameon=False,
          title="LEGEND")

ax.set_axis_off()
plt.show()

Python中怎么绘制矢量数据

同时对线宽和颜色进行调整

roadPalette = {'M': 'grey', 'S': "blue",
               'C': "magenta", 'Unknown': "lightgrey"}

lineWidths = {'M': 1, 'S': 2, 'C': 1.5, 'Unknown': 3}

fig, ax = plt.subplots(figsize=(10, 10))

for ctype, data in sjer_roads.groupby('RTTYP'):
    color = roadPalette[ctype]
    label = ctype
    
    data.plot(color=color,
              ax=ax,
              linewidth=lineWidths[ctype],
              label=label)
    
ax.set(title='Madera County Roads \n Pretty Colors')

ax.legend(loc='lower right',
          fontsize=20,
          frameon=False)

ax.set_axis_off()

plt.show()

png

向地图中添加点图层

接下来,向地图添加另一个图层,看看如何创建一个更复杂的地图,添加SJER_plot_centroids shapefile,并同时表示两个图层的图例

该点图层包含三种类型:grass,soil,trees

# 导入点图层
sjer_plots_path ="data/california/neon-sjer-site/vector_data/SJER_plot_centroids.shp"
sjer_plots = gpd.read_file(sjer_plots_path)
sjer_plots.head(5)

<div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; }

.dataframe tbody tr th {
    vertical-align: top;
}

.dataframe thead th {
    text-align: right;
}

</style> <table border="1" class="dataframe"> <thead> <tr > <th></th> <th>Plot_ID</th> <th>Point</th> <th>northing</th> <th>easting</th> <th>plot_type</th> <th>geometry</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>SJER1068</td> <td>center</td> <td>4111567.818</td> <td>255852.376</td> <td>trees</td> <td>POINT (255852.376 4111567.818)</td> </tr> <tr> <th>1</th> <td>SJER112</td> <td>center</td> <td>4111298.971</td> <td>257406.967</td> <td>trees</td> <td>POINT (257406.967 4111298.971)</td> </tr> <tr> <th>2</th> <td>SJER116</td> <td>center</td> <td>4110819.876</td> <td>256838.760</td> <td>grass</td> <td>POINT (256838.760 4110819.876)</td> </tr> <tr> <th>3</th> <td>SJER117</td> <td>center</td> <td>4108752.026</td> <td>256176.947</td> <td>trees</td> <td>POINT (256176.947 4108752.026)</td> </tr> <tr> <th>4</th> <td>SJER120</td> <td>center</td> <td>4110476.079</td> <td>255968.372</td> <td>grass</td> <td>POINT (255968.372 4110476.079)</td> </tr> </tbody> </table> </div>

就像上面所做的一样,创建一个字典来指定与每个图形类型相关联的颜色

pointsPalette = {'trees': 'chartreuse',
                 'grass': 'darkgreen', 'soil': 'burlywood'}

lineWidths = {'M': .5, 'S': 2, 'C': 2, 'Unknown': .5}

fig, ax = plt.subplots(figsize=(10, 10))

for ctype, data in sjer_plots.groupby('plot_type'):
    color = pointsPalette[ctype]
    label = ctype
    data.plot(color=color,
              ax=ax,
              label=label,
              markersize=100)
    
ax.set(title='Study area plot locations\n by plot type (grass, soil and trees)')

ax.legend(fontsize=20,
          frameon=True,
          loc=(1, .1),
          title="LEGEND")

ax.set_axis_off()
plt.show()

Python中怎么绘制矢量数据

将点图层叠加到道路图层

接下来,在道路图层上叠加绘制点数据,然后创建一个包含线和点的自定义图例

注意: 在这个例子中,两个图层的投影信息必须匹配

# Reproject the data
# 数据投影
sjer_roads_utm = sjer_roads.to_crs(sjer_plots.crs)
fig, ax = plt.subplots(figsize=(10, 10))

# 点图层绘制
for ctype, data in sjer_plots.groupby('plot_type'):
    color = pointsPalette[ctype]
    label = ctype # label参数对于图例的生成很重要
    data.plot(color=color,
              ax=ax,
              label=label,
              markersize=100)
# 道路图层绘制    
for ctype, data in sjer_roads_utm.groupby('RTTYP'):
    color = roadPalette[ctype]
    label = ctype    
    data.plot(color=color,
              ax=ax,
              linewidth=lineWidths[ctype],
              label=label)
    
ax.set(title='Study area plot locations\n by plot type (grass, soil and trees)')

ax.legend(fontsize=15,
          frameon=False,
          loc=('lower right'),
          title="LEGEND")

ax.set_axis_off()
plt.show()

上述就是小编为大家分享的Python中怎么绘制矢量数据了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI