如何基于频数表绘制小提琴图(不使用repeat函数)
问题描述
我有一份以频数表格式存储的大数据(原始数据量过大无法展开),数据示例如下:
value count year status 0 985572 2000 U 1 1857356 2000 U 2 3904079 2000 U 3 6399287 2000 U 4 9321185 2000 U 5 13093158 2000 U 6 16379938 2000 U 7 18409244 2000 U ... ... ... ... 95 3 2000 U 99 3 2000 U 100 5 2000 U 2 1 2000 B 3 9 2000 B 4 13 2000 B 5 19 2000 B 6 23 2000 B 7 80 2000 B 8 69 2000 B 9 82 2000 B ... ... ... ... 49 2 2000 B 50 1 2000 B 53 1 2000 B
我需要绘制小提琴图,要求x轴为year,y轴为value,按status分组展示分布,且分布要与count对应(而非当前得到的均匀分布小提琴图)。但因为数据量太大,无法使用Python的repeat函数展开数据,当前使用的代码如下:
plt.figure(figsize=(15, 8)) sns.violinplot(x='year', y='value', data=test, hue='status', inner='quart', palette = color)
当前得到的是不符合预期的均匀分布小提琴图。
解决方案
直接利用seaborn.violinplot的weights参数,将count列作为每个value的权重传入,无需展开原始数据就能让小提琴图的分布与频数对应。修改后的代码如下:
import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(15, 8)) sns.violinplot( x='year', y='value', data=test, hue='status', inner='quart', palette=color, weights='count' # 新增权重参数,关联频数列 ) plt.show()
这个参数会让每个value的频数(count值)参与分布密度的计算,最终生成的小提琴图能准确反映对应status下value的实际分布情况。
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

