本文绘制以上6种类型的柱状图
导入需要的包
#导入需要的包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
读取数据
df = sns.load_dataset("tips")
df_bar = df.groupby(by='size').agg({'tip':sum}).reset_index()
plt.bar(x='size',height = 'tip',data=df_bar)
# x-横坐标,分类变量(可以是数值型,也可以是字符型)
# height-纵坐标,数值型变量
plt.bar(x='size',height = 'tip',data=df_bar)
sns.despine() #去除图脊,默认去掉上边和右边
plt.bar(x='size',height = 'tip',data=df_bar)
sns.despine(left = True,bottom = True) #去除所有图脊
plt.yticks([])#不显示纵坐标
#遍历横纵坐标,将文本添加到具体的位置上
for x,y in zip(df_bar['size'],df_bar['tip']):
text = str(y)
xy=(x,y+5)
plt.annotate(text,xy=xy,fontsize=10,color="black",ha="center",va="baseline")
#数据准备
df_bar_1 = df.loc[df['sex'] == 'Male'].groupby(by='size').agg({'tip':sum}).reset_index()
df_bar_2 = df.loc[df['sex'] == 'Female'].groupby(by='size').agg({'tip':sum}).reset_index()
plt.bar(x='size',height = 'tip',data=df_bar_1,color='dodgerblue',alpha=0.5,label='Male')
plt.bar(x='size',height = 'tip',data=df_bar_2,color='tomato',alpha=0.5,bottom=df_bar_1['tip'],label='Female')
plt.legend() #显示图例
bar_width=0.3 #设置柱宽
df_bar_1['x_new'] = [i-bar_width/2 for i in np.arange(len(df_bar_1['size']))] #类别1横坐标左移半个柱宽
df_bar_2['x_new'] = [i+bar_width/2 for i in np.arange(len(df_bar_2['size']))] #类别2横坐标右移半个柱宽
plt.bar(x='x_new',height = 'tip',data=df_bar_1,color='dodgerblue',alpha=0.5,label='Male',width=bar_width)
plt.bar(x='x_new',height = 'tip',data=df_bar_2,color='tomato',alpha=0.5,label='Female',width=bar_width)
plt.legend() #显示图例
#数据准备
df_bar_percent = df.pivot_table(index='size',columns='sex',values='tip',aggfunc='sum').reset_index()
df_bar_total = df.groupby(by='size').agg({'tip':sum}).reset_index()
df_bar_percent = df_bar_percent.merge(df_bar_total,on='size',how='left')
df_bar_percent['Male_per'] = df_bar_percent['Male']/df_bar_percent['tip']
df_bar_percent['Female_per'] = df_bar_percent['Female']/df_bar_percent['tip']
#绘图
plt.bar(x='size',height = 'Male_per',data=df_bar_percent,color='dodgerblue',alpha=0.5,label='Male',width=0.6)
plt.bar(x='size',height = 'Female_per',data=df_bar_percent,color='tomato',alpha=0.5,bottom='Male_per',label='Female',width=0.6)