我打开一个csv文件,该文件将加拿大的一些省份与0到7之间的数字相关联。我将此数字作为新列添加到shapefile中。我想知道如何根据下面的颜色列表和十六进制代码分配颜色。
下面的代码有效,但是出来的颜色是由程序默认选择的,但我想根据颜色列表中的索引位置分配特定的颜色,颜色列表也存在于csv中,并添加为列到shapefile。
我尝试使用LinearSegmentedColormap但却无法使用它。任何帮助将不胜感激。
current colors that I don't want
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import csv
with open('canadadata.csv', 'r') as f:
reader = csv.reader(f, delimiter=",")
header = next(reader)
# Store states in dictionary keys, and price as values
forsaledata = {}
for row in reader:
k = int(row[3])
v = int(row[2])
forsaledata[k] = v
# open shapefile
canada = gpd.GeoDataFrame.from_file('lpr_000b16a_e.shp')
# create new column with shapefile data
canada['color'] = np.zeros(len(canada))
# assign colors to each province in the new column
canada.ix[0, 'color'] = int(forsaledata.get(0,8))
canada.ix[1, 'color'] = int(forsaledata.get(1,8))
canada.ix[2, 'color'] = int(forsaledata.get(2,8))
canada.ix[3, 'color'] = int(forsaledata.get(3,8))
canada.ix[4, 'color'] = int(forsaledata.get(4,8))
canada.ix[5, 'color'] = int(forsaledata.get(5,8))
canada.ix[6, 'color'] = int(forsaledata.get(6,8))
canada.ix[7, 'color'] = int(forsaledata.get(7,8))
canada.ix[8, 'color'] = int(forsaledata.get(8,8))
canada.ix[9, 'color'] = int(forsaledata.get(9,8))
canada.ix[10, 'color'] = int(forsaledata.get(10,8))
canada.ix[11, 'color'] = int(forsaledata.get(11,8))
canada.ix[12, 'color'] = int(forsaledata.get(12,8))
# establish colors, 9th color/index 8 is white
colors = ["#f7fbff", "#deebf7", "#c6dbef", "#9ecae1", "#6baed6", "#4292c6", "#2171b5", "#084594", "#ffffff"]
canada.plot(column='color')
plt.show()
答案 0 :(得分:0)
没关系,我明白了。它只是花了一些试验和错误才能做到正确。
colormap = []
colormap = LinearSegmentedColormap.from_list([0,1,2,3,4,5,6,7,8],colors)
canada.plot(column='color', cmap = colormap)