パンダのデータフレームを2つのプロットにプロットしようとしています。1つはmatplotlibpyplotの円グラフで、もう1つは海で生まれた棒グラフです。各グラフで、データフレームを並べ替えましたが、異なる列に基づいています。また、各グラフは、データフレームが並べ替えられたそれぞれの値を表しています。したがって、2つのグラフでは行の順序が異なります。このように、データフレーム内の同じインデックス(またはカテゴリ)がチャート上で異なる色で表示されるため、混乱を招きます。異なるチャートに同じ色のインデックスを作成するには、これをどのように修正できますか?
私のコード:
df = pd.DataFrame({"Total":totals,"Infected": infected},
index=category).sort_values("Total", ascending=False)
fig, ax = plt.subplots(ncols=2, nrows=1,figsize=(20,8))
#creating a pie chart with conditional explode option
threshold = new_train.shape[0]*threshold
if explode==-1:
ax[0].pie(df[df["Total"]>threshold]["Total"],
labels=df[df["Total"]>threshold].index.values,
autopct='%1.1f%%',shadow=False, startangle=rotation,
textprops={'fontsize': 15})
else:
ax[0].pie(df[df["Total"]>threshold]["Total"],
labels=df[df["Total"]>threshold].index.values,
autopct='%1.1f%%',shadow=False, startangle=rotation,
textprops={'fontsize': 15}, explode=explode)
ax[0].axis('equal')
ax[0].set_title(col_name)
#created a sorted bar chart
newdf = df[df["Total"]>threshold]
newdf.sort_values("Infected", ascending=False, inplace=True)
ax[1].set_xticklabels(category,rotation=45, horizontalalignment='right')
ax[1].set_title('Infected fractions')
ax[1] = sns.barplot(x=newdf.index, y="Infected",data=newdf,
order=newdf.index)#, orient='h')
plt.show()
たとえば、1.1.15200.1は円グラフでは青色ですが、棒グラフではオレンジ色です。
使用しているラベルの値に適した色を検索する辞書を作成する必要があります。以下は、データに対して行っているすべてのことをうまくカバーしている簡略版です。
# a dataframe from a list of lists
el = [['RED', 50, 1],
['GREEN', 30, 2],
['BLUE', 7, 3],
['YELLOW', 3, 4],
['ORANGE', 9, 5],
['BLACK', 1, 6]]
df = pd.DataFrame(el)
# since you are not using the entire dataframe
df_thres = df[df[1] > 1]
# make a fixed length color map manually
c = ['red', 'green', 'blue', 'yellow', 'orange']
clist1 = {i:j for i, j in zip(df_thres[0].values, c)}
# make an arbitrary-length colormap
cm = plt.get_cmap('rainbow')
c = [cm(1.0 * i/len(df_thres)) for i in range(len(df_thres))]
clist2 = {i:j for i, j in zip(df_thres[0].values, c)}
fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(11, 8))
# manual colors
# PIE PLOT: sort on the third column
newdf = df_thres.sort_values(2, ascending=False)
ax[0, 0].pie(newdf[2], labels=newdf[0], colors=[clist1[i] for i in newdf[0].values])
ax[0, 0].axis('square') # matplotlib 2.x only
# BAR PLOT: sort on the second column
newdf = df_thres.sort_values(1, ascending=False)
ax[0, 1].bar(newdf[0], newdf[1], color=[clist1[i] for i in newdf[0].values])
#----------------
# arbitrary-length generated colorlist
newdf = df_thres.sort_values(2, ascending=False)
ax[1, 0].pie(newdf[1], labels=newdf[0], colors=[clist2[i] for i in newdf[0].values])
ax[1, 0].axis('square') # matplotlib 2.x only
newdf = df_thres.sort_values(1, ascending=False)
ax[1, 1].bar(newdf[0], newdf[1], color=[clist2[i] for i in newdf[0].values])
これが私が得た出力です。下の行の色はラベルの付いた色ではありませんが、一貫しています。(また、ここでは両方のプロットにmatplotlibを使用していることに注意してください)
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加