def chloropleth(self, query, color = "Blues"):
"""shows a chloropleth map of crimes
Args:
query: name of sql
"""
self.load()
data = pd.read_sql_query(con=self.con, sql=query)
points = self.gen_points(data, self.data_map)
self.data_map['count'] = self.data_map['poly'].map(lambda x: len(list(filter(prep(x).contains, points))))
self.data_map['density_m'] = self.data_map['count'] / self.data_map['area_m']
self.data_map['density_km'] = self.data_map['count'] / self.data_map['area_km']
self.data_map.replace(to_replace={'density_m': {0: np.nan}, 'density_km': {0: np.nan}}, inplace=True)
breaks = nb(
self.data_map[self.data_map['density_km'].notnull()].density_km.values,
initial=300,
k=5)
jb = pd.DataFrame({'jenks_bins': breaks.yb}, index=self.data_map[self.data_map['density_km'].notnull()].index)
self.data_map = self.data_map.join(jb)
self.data_map.jenks_bins.fillna(-1, inplace=True)
jenks_labels = ["<= %0.1f/km$^2$(%s communities)" % (b, c) for b, c in zip(
breaks.bins, breaks.counts)]
jenks_labels.insert(0, 'None (%s communities)' % len(self.data_map[self.data_map['density_km'].isnull()]))
cmap = plt.get_cmap(color)
self.data_map['patches'] = self.data_map['poly'].map(lambda x: PolygonPatch(x, ec='#555555', lw=.2, alpha=1., zorder=4))
pc = PatchCollection(self.data_map['patches'], match_original=True)
norm = Normalize()
pc.set_facecolor(cmap(norm(self.data_map['jenks_bins'].values)))
self.ax.add_collection(pc)
cb = self.gen_colorbar(colors=len(jenks_labels), color_map=cmap, shrink=0.5, labels=jenks_labels)
cb.ax.tick_params(labelsize=6)
plt.tight_layout()
plt.show()
评论列表
文章目录