分类条形图

发布于:2024-05-23 ⋅ 阅读:(28) ⋅ 点赞:(0)

一、sns.barplot()

sns.barplot接口介绍

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# 创建数据
data = {
    'sites': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
    'category': ['x', 'x', 'y', 'x', 'y', 'y', 'x', 'z', 'z'],
    'value': [1, 2, 3, 4, 6, 5, 6, 7, 10],
}
df = pd.DataFrame(data)

# 使用seaborn绘制分类柱状图
plt.figure(figsize=(8, 6))
sns.barplot(data=df, x='sites', y='value', hue='category', capsize=0.1)

# 添加标题和标签
plt.title('Categorical Bar Plot')
plt.xlabel('Sites')
plt.ylabel('Values')
# 显示图形
plt.show()

在这里插入图片描述

二、plt.bar()

1、不同分组之间有间隔

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm

# 设置全局字体和字号
font = {'family': 'Times New Roman', 'size': 18}
plt.rc('font', **font)

# 设置柱状图数据样本
n_groups = 4
means_1 = (90, 55, 40, 65)
std_1 = (2, 3, 4, 1)

means_2 = (85, 62, 54, 20)
std_2 = (3, 5, 2, 3)

means_3 = (70, 45, 55, 30)
std_3 = (1, 2, 3, 4)

# 准备颜色渐变
cmap = plt.get_cmap('coolwarm')
colors_1 = [cmap(i) for i in np.linspace(0, 1, n_groups)]
cmap = plt.get_cmap('PiYG')
colors_2 = [cmap(i) for i in np.linspace(0, 1, n_groups)]
cmap = plt.get_cmap('YlGn')
colors_3 = [cmap(i) for i in np.linspace(0, 1, n_groups)]

# 绘制柱状图
fig, ax = plt.subplots(figsize=(8, 5))
index = np.arange(n_groups)
bar_width = 0.25

opacity = 0.8
error_config = {'ecolor': '0.3'}

rects1 = ax.bar(index, means_1, bar_width, capsize=3,
                alpha=opacity, color=colors_1,
                yerr=std_1, error_kw=error_config,
                label='x')

rects2 = ax.bar(index + bar_width, means_2, bar_width, capsize=3,
                alpha=opacity, color=colors_2,
                yerr=std_2, error_kw=error_config,
                label='y')

rects3 = ax.bar(index + 2 * bar_width, means_3, bar_width, capsize=3,
                alpha=opacity, color=colors_3,
                yerr=std_3, error_kw=error_config,
                label='z')


# 添加数据标签(显示在柱子上方中央)
def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width() / 2., 1.05 * height,
                '{:.0f}'.format(height),
                ha='center', va='bottom')


autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# 添加标签、标题和图例
ax.set_xlabel('Group', font)
ax.set_ylabel('Scores', font)
ax.set_xticks(index + bar_width)
ax.set_xticklabels(('10', '20', '30', '40'))
ax.legend(loc='best', ncol=3, frameon=False)

# 设置坐标轴字号为新罗马
for tick in ax.xaxis.get_minor_ticks():
    tick.label1.set_fontsize(16)
    tick.label1.set_fontname('Times New Roman')

for tick in ax.yaxis.get_minor_ticks():
    tick.label1.set_fontsize(16)
    tick.label1.set_fontname('Times New Roman')

plt.tight_layout()
plt.show()

在这里插入图片描述

2、不同分组之间没有间隔

import pandas as pd
import matplotlib.pyplot as plt

types = ['x', 'y', 'z']
# 创建数据
df = {
    'sites': ['A', 'A', 'A', 'B', 'B'],
    'cros': ['x', 'y', 'z', 'y', 'z'],
    'TET': [3, 2, 3, 4, 6],
    'std': [1, 1, 2, 1, 1],
}
dff = pd.DataFrame(df)
sites_name = dff['sites'].unique()
print(sites_name)
# 设置颜色映射
colors = {'x': 'red', 'y': 'green', 'z': 'blue'}
cnt = 0
for i in range(len(sites_name)):
    print(i)
    site = sites_name[i]
    data = dff[dff.sites == site]
    print(data)
    for j in range(len(data)):
        print(j)
        index = cnt + j
        cro = data['cros'][index]
        plt.bar(index, data['TET'][index], yerr=data['std'][index], capsize=5, label=cro,
                color=colors[cro])
    cnt += len(data)

plt.legend(dff['cros'].unique())
# 设置 x 轴刻度标签
plt.xticks(range(len(dff['sites'])), dff['sites'])
plt.show()

在这里插入图片描述

import pandas as pd
import matplotlib.pyplot as plt

# 提供的数据
df = {
    'sites': ['A', 'A', 'A', 'B', 'B'],
    'cros': ['x', 'y', 'z', 'y', 'z'],
    'TET': [3, 2, 3, 4, 6],
    'std': [1, 1, 2, 1, 1],
}
dff = pd.DataFrame(df)
colors = {'x': 'red', 'y': 'green', 'z': 'blue'}
# 根据'sites'和'cros'列对'TET'列进行分组,并计算每组的平均值
grouped_data = dff.groupby(['sites', 'cros'])['TET'].mean().reset_index()

print(grouped_data)
# 创建一个新的Figure对象和一个子图
fig, ax = plt.subplots()

# 绘制柱状图
ax.bar(range(len(grouped_data)), grouped_data['TET'], color=[colors[c] for c in grouped_data['cros']])

# 设置x轴刻度标签
ax.set_xticks(range(len(dff['sites'])), dff['sites'])

# 添加标签和标题
ax.set_xlabel('Group')
ax.set_ylabel('Mean TET')
ax.set_title('Mean TET by Group')

# 显示图形
plt.show()

在这里插入图片描述