matplotlibの水平棒グラフとしての離散分布の例を使用して、2017年のシュロプシャー選挙での投票のシェアを示すグラフを作成しました。
しかし、データの操作方法がわからなかったため、プログラムに手動でデータを入力する必要がありました。これは明らかに自分の無知によるものです。
関連するデータがCSVファイルに含まれているため、データフレームとして読み込むことができます。
このグラフの入力に似たデータの形式を変更する方法についてアドバイスが必要でした。
それが何であるかはわかりませんが、キーと値を持つ辞書タイプのようです。
category_names = ['Labour', 'LD', 'Indep', 'Green', 'Tory']
results = {'Abbey': [16, 56, 4,0, 24],
'Albrighton': [0, 0, 32, 0, 68],
'Alveley & Claverley': [0, 25, 0, 0, 75],
'Bagley': [30, 30, 0, 0, 40],
'Battlefield': [34, 0, 0, 9, 57],
'Bayston Hill, Column & Sutton': [53, 4, 3, 7, 33],
'Belle Vue': [43,28,0,5,24]}
pandasデータフレームとして入力したときに、csvファイルから直接このようにフォーマットするデータを取得しようとしています。
値の方法と方法を試しましたが、to_dict
データが似ているように見えますが、完全には正しくありません。
'Party'
y軸としてresults
と、category_names
OPからのデータimport pandas as pd
import matplotlib.pyplot as plt
# plt configuration parameters
plt.style.use('seaborn')
plt.rcParams['figure.figsize'] = (16.0, 10.0)
# setup dataframe using the dict provided in the OP
df = pd.DataFrame(results, index=category_names)
# display(df)
Abbey Albrighton Alveley & Claverley Bagley Battlefield Bayston Hill, Column & Sutton Belle Vue
Labour 16 0 0 30 34 53 43
LD 56 0 25 30 0 4 28
Indep 4 32 0 0 0 3 0
Green 0 0 0 0 9 7 5
Tory 24 68 75 40 57 33 24
# plot
ax = df.plot.barh(stacked=True, cmap='tab10', figsize=(16, 10))
# annotations:
for p in ax.patches:
left, bottom, width, height = p.get_bbox().bounds
if width > 0:
ax.annotate(f'{width:0.0f}', xy=(left+width/2, bottom+height/2), ha='center', va='center')
'Ward'
y軸としてpandas.DataFrame.T
スワップするIndex
と、Columns
'Ward'
これでインデックス'Party'
になり、列になります# using df from Option 1
# transpose df so Party is the in the columns and Ward is the index
dft = df.T
# display(dft)
Labour LD Indep Green Tory
Abbey 16 56 4 0 24
Albrighton 0 0 32 0 68
Alveley & Claverley 0 25 0 0 75
Bagley 30 30 0 0 40
Battlefield 34 0 0 9 57
Bayston Hill, Column & Sutton 53 4 3 7 33
Belle Vue 43 28 0 5 24
# plot
ax = dft.plot.barh(stacked=True, figsize=(16, 10))
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))
# annotations:
for p in ax.patches:
left, bottom, width, height = p.get_bbox().bounds
if width > 0:
ax.annotate(f'{width:0.0f}', xy=(left+width/2, bottom+height/2), ha='center', va='center')
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加