You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python可视化求助:多环境日志计数的分组柱状图绘制失败

分组柱状图解决方案

首先明确:hist方法是用来绘制数据分布直方图的,不适合做这种分类变量的分组对比,实现这类需求应该用bar方法。

示例测试数据

import matplotlib.pyplot as plt
import numpy as np

# 测试数据
environments = ["DEV", "UAT", "STG", "PRD"]
plugin_logs = [120, 95, 80, 150]
audit_logs = [70, 60, 55, 100]

实现代码

# 设置柱状图宽度,控制两组柱子的间隔
bar_width = 0.35
# 生成x轴基础位置(对应4个环境的索引)
x = np.arange(len(environments))

# 绘制两组柱状图,通过偏移位置实现分组
plt.bar(x - bar_width/2, plugin_logs, width=bar_width, label="Plugin Logs")
plt.bar(x + bar_width/2, audit_logs, width=bar_width, label="Audit Logs")

# 配置图表标签与样式
plt.xlabel("环境")
plt.ylabel("日志计数")
plt.title("各环境日志计数对比")
plt.xticks(x, environments)  # 将x轴数值替换为环境名称
plt.legend()

# 自动调整布局,避免标签、标题被截断
plt.tight_layout()
plt.show()

核心逻辑说明

  • 用np.arange生成x轴的基础索引位置,通过加减bar_width/2让两组柱子在同一环境下错开,避免重叠
  • xticks方法负责将x轴的数值索引替换为可读性更强的环境名称
  • tight_layout自动优化图表元素的位置,解决标签溢出问题

内容的提问来源于stack exchange,提问作者Jon Rothlander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 05:47:02