【发布时间】:2021-04-12 23:51:59
【问题描述】:
我正在开发 Jupyter Notebbok,使用 geopandas 在地图(边界)中的特定纬度和经度处绘制标记,但我有大约 40,000 个位置,我需要用基于颜色的方式标记(和着色)每个位置有条件的。
Geopandas 数据框gdf 的屏幕截图如下:
代码片段:
import matplotlib.patches as mpatches
# we have range of values from 0-15000
threshold1 = [8000,'#e60000']
threshold2 = [500,'#de791e']
threshold3 = [200,'#ff00ff']
threshold4 = [0 ,'#00ff0033']
# Create a dictionary of colors based on threshold
color_dict = {}
for x in gdf.n.to_list():
if x>= threshold1[0] : color_dict[x] = threshold1[1]
if x>= threshold2[0] and x<threshold1[0]: color_dict[x] = threshold2[1]
if x>= threshold3[0] and x<threshold2[0]: color_dict[x] = threshold3[1]
if x<threshold3[0] : color_dict[x] = threshold4[1]
# Set labels for the legend
a_patch = mpatches.Patch(color = threshold1[1],
label= str(threshold1[0]) + '-' + str(max(gdf.n.to_list())))
b_patch = mpatches.Patch(color = threshold2[1],
label= str(threshold2[0]) + '-' + str(threshold1[0]))
c_patch = mpatches.Patch(color = threshold3[1],
label= str(threshold3[0]) + '-' + str(threshold2[0]))
d_patch = mpatches.Patch(color = threshold4[1],
label= str(min(gdf.n.to_list())) + '-' + str(threshold3[0]))
ax = gdf.plot(markersize=0 ,figsize = (20,20))
usa.geometry.boundary.plot(color=None,edgecolor='k',linewidth = 0.5, ax = ax)
# There are ~40,000 values to be iterated here
for x, y, label in zip(tqdm(gdf.geometry.x), gdf.geometry.y, gdf.n):
ax.annotate('X', weight = 'bold', xy=(x, y), xytext=(x, y), fontsize= 8,color = color_dict[label], ha='center')
sleep(0.1)
ax.annotate(label, xy=(x, y), xytext=(x, y), fontsize= 8, color = color_dict[label], ha='center')
usa.apply(lambda x: ax.annotate(text = x.NAME, xy=x.geometry.centroid.coords[0], ha='center', fontsize= 2,color='black'),axis=1);
plt.xlim([-130,-60])
plt.ylim([20,55])
plt.legend(handles=[a_patch, b_patch, c_patch, d_patch])
plt.savefig("state.png",pad_inches=0, transparent=False, format = 'png')
我知道是这条线花费的时间最多:
for x, y, label in zip(tqdm(gdf.geometry.x), gdf.geometry.y, gdf.n):
ax.annotate('X', weight = 'bold', xy=(x, y), xytext=(x, y), fontsize= 8,color = color_dict[label], ha='center')
sleep(0.1)
但我想不出任何其他方法来标记每个坐标而不循环。请帮助我让它更快。 2-3个小时对我的工作来说太不合理了!谢谢!
我在代码中使用的一些参考资料:
【问题讨论】:
-
除非您正在制作壁画,否则我不确定您要使用 40K 标记点制作什么样的情节。 :)。不要问显而易见的问题,但是为什么您抱怨的循环中有
sleep()命令很慢? 40K * 0.1 秒 = 1.1 小时就在那里...... -
我疯了!我检查了所有内容,但没有考虑睡眠功能。我的上帝!谢谢!我确实需要 40K 点,但现在只需 3 分钟。
-
我建议您比较运行 1000 行、有和没有
tqdm和sleep之间的时间。上面提到的使用 sleep 会增加很多时间,打印出来也会消耗时间。 -
这是秘密摄影秀之一吗?我被恶作剧了吗? ;)
-
@pazitos10,是的,sleep() 函数是罪魁祸首。 @ AirSquid——不知道你提到的这个节目,但感谢你的帮助。代码已修复!
标签: python performance loops for-loop geopandas