matplotlib 如何可视化更好的分离列[duplicate]

shyt4zoc  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(153)

此问题在此处已有答案

How to create a grouped bar plot(4个答案)
3天前关闭。
我有这个 Dataframe

SEED_WORD Metaphoric_Seed  size
0    activity         literal     9
1    activity      metaphoric     1
2       allow         literal     1
3       allow      metaphoric     1
4        back         literal     3
5    backbone         literal     4
6    backbone      metaphoric    12
7        base         literal    14
8     bracket         literal     2
9   establish         literal     4`

对于每一个不同的种子词,我希望有字面和隐喻的大小。
为了得到它,我编写了:
df_all_annotated.groupby(['SEED_WORD','Metaphoric_Seed'])['SEED_WORD','Metaphoric_Seed'].count().plot.bar()
然后得到了这个

问题是,我希望每个种子词都有相同的颜色条,一种颜色代表隐喻,一种颜色代表字面意思。我希望我解释得很清楚

ukqbszuj

ukqbszuj1#

这是seaborn的一个很好的用例:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.DataFrame({'SEED_WORD': {0: 'activity', 1: 'activity', 2: 'allow', 3: 'allow', 4: 'back', 5: 'backbone', 6: 'backbone', 7: 'base', 8: 'bracket', 9: 'establish'}, 'Metaphoric_Seed': {0: 'literal', 1: 'metaphoric', 2: 'literal', 3: 'metaphoric', 4: 'literal', 5: 'literal', 6: 'metaphoric', 7: 'literal', 8: 'literal', 9: 'literal'}, 'size': {0: 9, 1: 1, 2: 1, 3: 1, 4: 3, 5: 4, 6: 12, 7: 14, 8: 2, 9: 4}})

sns.barplot(df, x='SEED_WORD', y='size', hue='Metaphoric_Seed')
plt.show()

输出:

zbq4xfa0

zbq4xfa02#

早上好,
对我来说,我认为你想做一个直方图,所以这里有一个代码来做一个堆叠的直方图。但是我认为这个代码可以很好地缩短'' import matplotlib.pyplot as plt import panda as pd

df = pd.read_excel('data.xlsx')
df =df.set_index('SEED_WORD')

df_meta = df[df['Metaphoric_Seed']  == "metaphoric"]
df_lit = df[df['Metaphoric_Seed']  != "metaphoric"]
index =[]
for k in df_meta.index.tolist():
    index.append( df_lit.index.tolist().index(k))
    
plt.bar( df_lit.index.unique().tolist(),df_lit['size']
        ,  label = 'Literal')
plt.bar( df_meta.index.unique().tolist(),df_meta['size'],
        bottom = [df_lit['size'][j] for j in index],
        label = 'Metaphoric')
 
jours = df.index.unique().tolist()
plt.xticks(range(len(jours)),jours, rotation = 45)

plt.legend()
plt.show()

“"以下是结果enter image description here

相关问题