繁体   English   中英

使用 Python、Pandas 和 Geopandas 绘制英国选举结果

[英]Plotting the UK election results using Python, Pandas and Geopandas

as an exercise I am trying to plot out the UK's general election results from 2017. I have used Pandas to manipulate my dataframe and geopandas to visualise the results where every region is coloured by the winning party, conservative: blue, labour: red etc. ..

我已经设法将 plot 弄出来了,但无论我做什么 - 颜色都没有正确显示,下面我附上了我的代码,我的 output 以及 Z78E6221F6393D1356681DB398F14CED 应该是什么样子。 任何帮助将不胜感激。

我的代码:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import multipolygon, polygon, Polygon, MultiPolygon
%matplotlib inline

uk_map = gpd.read_file('Westminster_Parliamentary_Constituencies__December_2017__UK_BGC_V2.shp')
#shape file of the uk

df = pd.read_csv('uk_election_data_v2.csv')
#election results

uk_map.rename(columns={'PCON17NM':'Constituency'}, inplace=True)
uk_map.sort_values('Constituency', inplace=True)

df.sort_values('Constituency', inplace=True)

party_colours={'Conservative':'#0087dc',
               'Liberal Democrat':'#FDBB30',
               'Labour':'#d50000',
               'SNP':'#FFF95D',
               'Green':'#00FF00',
               'Independent':'#800080',
               'Sinn Fein':'#228B22',
               'Democratic Unionist':'#808080',
               'Plaid Cymru':'#FF5733'
              }
#dictionary to assign the colours to each winning party

df['winner_fill']=df['2017_winner'].apply(lambda s: party_colours.get(s,"#aaaaaa"))
#new column that applies the colour for the winning party

election_results = uk_map.merge(df, on='Constituency')
#merge the shape and df together

election_results.plot('winner_fill', figsize=(12,12))

[预期输出] 在此处输入图像描述

[我的输出] 在此处输入图像描述

我认为这个问题apply

df['winner_fill']=df['2017_winner'].apply(lambda s: party_colours.get(s,"#aaaaaa"))

改用map

df['winner_fill'] = df['2017_winner'].map(lambda s: party_colours.get(s,"#aaaaaa"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM