Python 在matplotlib(或seaborn)中为x值着色并在图例中显示,而不是以记号显示
我有一个大的df,我将其分组以绘制在条形图中。 我做了这个模拟df来说明我的意思。(我创造它的乐趣太多了…) 然后我对它进行分组并绘制:Python 在matplotlib(或seaborn)中为x值着色并在图例中显示,而不是以记号显示,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,我有一个大的df,我将其分组以绘制在条形图中。 我做了这个模拟df来说明我的意思。(我创造它的乐趣太多了…) 然后我对它进行分组并绘制:my.groupby('tv-show').sum().plot(kind='bar',stacked=True) 我想要的是一个情节,其中电视节目的名称在一个图例中而不是在x轴下,并且节目有不同的颜色(当然)。试试sns: new_df = my.groupby('tv-show').sum().reset_index() sns.barplot(x='t
my.groupby('tv-show').sum().plot(kind='bar',stacked=True)
我想要的是一个情节,其中电视节目的名称在一个图例中而不是在x轴下,并且节目有不同的颜色(当然)。试试sns:
new_df = my.groupby('tv-show').sum().reset_index()
sns.barplot(x='tv-show', y='episodes',
hue='tv-show', data=new_df)
输出:
另一种使用
matplotlib
的替代解决方案可能类似
import matplotlib.patches as mpatches
fig, ax = plt.subplots(figsize=(8, 6))
# Your dataframe "my" here
ax_ = my.groupby('tv-show').sum().plot(kind='bar', stacked=True, legend=False, ax=ax)
colors = ['r', 'g', 'b']
handles = []
for col, lab, patch in zip(colors, np.unique(my['tv-show']), ax_.axes.patches):
patch.set_color(col)
handles.append(mpatches.Patch(color=col, label=lab))
ax_.legend(handles=handles)
ax_.set_xticklabels([])
直接使用熊猫:
ax = my.groupby('tv-show').sum().transpose().plot.bar()
ax.set_xticks([])
对于每个具有不同颜色的节目,您可以查看帖子:如何删除x轴下的电视节目名称?返回
ax=sns.barplot(…)
和ax.set\xticklabels([])
。
ax = my.groupby('tv-show').sum().transpose().plot.bar()
ax.set_xticks([])