如何不使用DataFrame绘制seaborn countplot计数图
完全可以,以下是三种可行的实现方式,可根据你的数据场景选择:
方法1:直接传入列表调用countplot
sns.countplot()的x参数原生支持传入列表、数组等序列数据,无需提前封装为DataFrame。如果你的原始数据是单条的分类观测记录,直接传入即可:
import seaborn as sns import matplotlib.pyplot as plt # 手动构造5类心跳的观测列表,按你需要的计数调整各类别的重复次数 heartbeat_list = ['窦性心律']*2800 + ['房性早搏']*1500 + ['室性早搏']*900 + ['房颤']*600 + ['传导阻滞']*300 ax = sns.countplot(x=heartbeat_list) # 调整纵轴范围为0-3000 ax.set_ylim(0, 3000) ax.set_xlabel("心跳类别") ax.set_ylabel("计数") plt.show()
方法2:已知分类计数值时直接用barplot
如果你已经明确每个类别的具体计数,不需要seaborn自动统计频次,用barplot实现更高效,无需构造大量重复元素的列表:
import seaborn as sns import matplotlib.pyplot as plt # 手动输入分类和对应计数 categories = ['窦性心律', '房性早搏', '室性早搏', '房颤', '传导阻滞'] count_values = [2800, 1500, 900, 600, 300] ax = sns.barplot(x=categories, y=count_values) ax.set_ylim(0, 3000) ax.set_xlabel("心跳类别") ax.set_ylabel("计数") plt.show()
方法3:countplot搭配weight参数
如果你需要保留countplot的调用逻辑,又不想生成长列表,可构造极简DataFrame搭配weight参数实现:
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt # 手动构造小型DataFrame df = pd.DataFrame({ "class": ['窦性心律', '房性早搏', '室性早搏', '房颤', '传导阻滞'], "count": [2800, 1500, 900, 600, 300] }) ax = sns.countplot(x="class", data=df, weight="count") ax.set_ylim(0, 3000) plt.show()
内容的提问来源于stack exchange,提问作者Heather Mcall
相关产品推荐
相关产品推荐

