获取固定的图例颜色映射

2024-04-16 18:51:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我和熊猫有三块地。其中一个图中没有数字“2”,因此所有类别的颜色都与其他两个不同。有没有可能有一个固定的颜色图?你知道吗

以下是三个情节:

enter image description here

enter image description here

enter image description here

下面是其中一幅图的构造:

fig, ax = plt.subplots()

columns = ['Radius', 'FRC', 'Scoring']
df = pd.DataFrame(bestof10, columns=columns)
out = {}
for column in columns:
    out[column] = pd.value_counts(df[column])

uniq_df = pd.DataFrame(out).fillna(0)

test = uniq_df.T.plot(kind="bar", stacked=True, ax =ax,rot=0)

#ax.legend(loc='best');
ax.set_ylabel("frequency")
plt.legend(bbox_to_anchor=(1.2, 1), loc='upper right', ncol=1)
plt.savefig("WithoutInfluenceOfParameterBestOf10.png",bbox_inches='tight')

Tags: columnsdataframedf颜色columnplt数字ax
1条回答
网友
1楼 · 发布于 2024-04-16 18:51:45

一种方法是填充数据框中所有不存在的值(我无法像您那样定位图例,这就是我使用GridSpec的原因):

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import gridspec

gs = gridspec.GridSpec(ncols = 5, nrows = 12)
fig = plt.figure(figsize=(4,8))
axes = [
    fig.add_subplot(gs[4*i:4*(i+1),:-1]) for i in range(3)
]

columns = ['Radius', 'FRC', 'Scoring']
dfs = [
    pd.DataFrame({
        'FRC' :     sum([[i+1]*n for i,n in enumerate([0,0,3,7,0,0,0,])],[]),
        'Radius' :  sum([[i+1]*n for i,n in enumerate([0,0,1,9,0,0,0,])],[]),
        'Scoring' : sum([[i+1]*n for i,n in enumerate([1,0,1,2,1,2,3,])],[]),
    }),
    pd.DataFrame({
        'FRC' :     sum([[i+1]*n for i,n in enumerate([0,1,8,11,0,0,0,])],[]),
        'Radius' :  sum([[i+1]*n for i,n in enumerate([0,0,5,15,0,0,0,])],[]),
        'Scoring' : sum([[i+1]*n for i,n in enumerate([3,2,3,3, 2,3,4,])],[]),
    }),
    pd.DataFrame({
        'FRC' :     sum([[i+1]*n for i,n in enumerate([0,1,8,11,0,0,0,])],[]),
        'Radius' :  sum([[i+1]*n for i,n in enumerate([0,0,5,15,0,0,0,])],[]),
        'Scoring' : sum([[i+1]*n for i,n in enumerate([3,2,3,3, 2,3,4,])],[]),
    }),
]
#collect all possible values in a set() by looping through all 
#dataframes
all_vals=set()    
for df in dfs:
    for column in columns:
        all_vals.update(df[column])

#looping through the data frames again to produce the plots           
for bestof,ax in zip(dfs, axes):    
    df = pd.DataFrame(bestof, columns=columns)
    out = {}
    for column in columns:
        out[column] = pd.value_counts(df[column])

        for val in all_vals:
            if val not in out[column]:
                out[column][val] = 0

    uniq_df = pd.DataFrame(out).fillna(0)

    test = uniq_df.T.plot(kind="bar", stacked=True, ax=ax, rot=0)

    ax.legend(loc='best');
    ax.set_ylabel("frequency")
    ax.legend(bbox_to_anchor=(1.2, 1), loc='upper right', ncol=1)
fig.tight_layout()
plt.show()

此代码生成下图: bar plots with correct legends

希望这有帮助。你知道吗

相关问题 更多 >