如何在柱状图中绘制带有多个数值的子类别
当然可以实现
你可以用Python的matplotlib库来完成这个需求,下面是具体的实现示例,以两种常见的可视化方式为例:
方式1:箱线图(展示数值分布)
适合直观呈现每个子类别下数值的分布特征:
import matplotlib.pyplot as plt import numpy as np # 你的数据字典 data = {'A': {'pos': [3, 5, 7], 'neg': [8, 10, 11]}, 'B': {'pos': [4, 7, 8], 'neg': [7, 10, 12]}, 'C': {'pos': [1, 3, 4], 'neg': [2, 8, 8]}} # 提取数据 categories = list(data.keys()) pos_values = [data[cat]['pos'] for cat in categories] neg_values = [data[cat]['neg'] for cat in categories] # 绘图设置 fig, ax = plt.subplots(figsize=(8, 6)) box_width = 0.35 x = np.arange(len(categories)) # 绘制正负类别箱线图 ax.boxplot(pos_values, positions=x - box_width/2, widths=box_width, patch_artist=True, boxprops=dict(facecolor='#66b3ff')) ax.boxplot(neg_values, positions=x + box_width/2, widths=box_width, patch_artist=True, boxprops=dict(facecolor='#ff9999')) # 添加标注 ax.set_title('Category-wise Positive & Negative Values') ax.set_ylabel('Value') plt.xticks(x, categories) ax.legend([plt.Rectangle((0,0),1,1,fc='#66b3ff'), plt.Rectangle((0,0),1,1,fc='#ff9999')], ['Positive', 'Negative']) plt.tight_layout() plt.show()
方式2:散点图(展示单个数值点)
适合展示每个子类别下的所有具体数值,通过抖动避免点重叠:
import matplotlib.pyplot as plt import numpy as np data = {'A': {'pos': [3, 5, 7], 'neg': [8, 10, 11]}, 'B': {'pos': [4, 7, 8], 'neg': [7, 10, 12]}, 'C': {'pos': [1, 3, 4], 'neg': [2, 8, 8]}} categories = list(data.keys()) x = np.arange(len(categories)) box_width = 0.35 # 整理散点数据 x_pos = np.repeat(x - box_width/2, [len(v) for v in pos_values]) y_pos = [val for sublist in pos_values for val in sublist] x_neg = np.repeat(x + box_width/2, [len(v) for v in neg_values]) y_neg = [val for sublist in neg_values for val in sublist] # 绘图 fig, ax = plt.subplots(figsize=(8, 6)) ax.scatter(x_pos + np.random.normal(0, 0.02, len(x_pos)), y_pos, color='#66b3ff', label='Positive') ax.scatter(x_neg + np.random.normal(0, 0.02, len(x_neg)), y_neg, color='#ff9999', label='Negative') # 添加标注 ax.set_title('Category-wise Positive & Negative Values') ax.set_ylabel('Value') plt.xticks(x, categories) ax.legend() plt.tight_layout() plt.show()
你可以根据想要的最终可视化效果选择对应的实现方式。
内容的提问来源于stack exchange,提问作者Jozef
相关产品推荐
相关产品推荐

