pyecharts画箱线图
时间: 2023-09-06 14:10:08 浏览: 64
以下是使用 Pyecharts 绘制箱线图的示例代码:
```python
from pyecharts import options as opts
from pyecharts.charts import Boxplot
# 构造数据
data = [
[850, 740, 900, 1070, 930, 850, 950, 980, 980, 880],
[960, 940, 960, 940, 880, 800, 850, 880, 900],
[880, 880, 880, 860, 720, 720, 620, 860],
[890, 810, 810, 820, 800, 770, 760, 740, 750],
[890, 840, 780, 810, 760, 810, 790, 810, 820, 850],
]
# 创建 Boxplot 对象
boxplot = (
Boxplot()
.add_xaxis(["A", "B", "C", "D", "E"])
.add_yaxis("", box_data=data)
.set_global_opts(
title_opts=opts.TitleOpts(title="箱线图示例"),
xaxis_opts=opts.AxisOpts(type_="category"),
yaxis_opts=opts.AxisOpts(type_="value")
)
)
# 渲染图表
boxplot.render("boxplot.html")
```
解释一下代码:
1. `data` 是一个包含多个列表的列表,每个内部列表都是箱线图中一个箱子的数据。
2. 创建 `Boxplot` 对象。
3. 使用 `add_xaxis` 方法添加 x 轴数据。
4. 使用 `add_yaxis` 方法添加 y 轴数据,第一个参数为空字符串表示不需要图例。
5. 使用 `set_global_opts` 方法设置全局选项,包括标题、x 轴和 y 轴的选项。
6. 使用 `render` 方法将图表渲染为 HTML 文件。
如果需要在 Jupyter Notebook 中显示图表,可以使用 `render_notebook` 方法代替 `render` 方法,代码如下:
```python
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot as driver
make_snapshot(driver, boxplot.render(), "boxplot.png")
```
这将把图表渲染为 PNG 图片,并将其显示在 Jupyter Notebook 中。