age_preg_bar = px.box(risk_factor_df, x="age_cat", y="Num of pregnancies", color_discrete_sequence=["darkblue"], points="outliers", category_orders=["Teenager", "Twenties", "Thirties", "Forties", "Fifties", "Seventy and over"]) age_preg_bar.update_xaxes(title="Age Category") age_preg_bar.update_yaxes(title="Number of Pregnancies") age_preg_bar.update_layout(title="Distribution of number of pregnancies per age group") age_preg_bar.show()用pyecharts绘制代码
时间: 2023-07-21 13:26:03 浏览: 383
以下是使用pyecharts绘制类似的箱线图的代码:
```python
from pyecharts.charts import Boxplot
from pyecharts import options as opts
import pandas as pd
# 读入数据
risk_factor_df = pd.read_csv('risk_factor.csv')
# 按照年龄分组
groups = risk_factor_df.groupby('age_cat')['Num of pregnancies'].apply(list).reset_index()
# 绘制箱线图
boxplot = Boxplot().add_xaxis(groups['age_cat'].tolist()) \
.add_yaxis("", box_data=groups['Num of pregnancies'].tolist(), \
color="#5470c6", \
itemstyle_opts=opts.ItemStyleOpts(border_color="#5470c6",
border_width=2,
border_type="solid")) \
.set_global_opts(title_opts=opts.TitleOpts(title="Distribution of number of pregnancies per age group"),
yaxis_opts=opts.AxisOpts(name="Number of Pregnancies"),
xaxis_opts=opts.AxisOpts(name="Age Category"))
boxplot.render_notebook()
```
需要注意的是,pyecharts中的Boxplot图并没有针对离群点(points="outliers")进行单独的处理,而是将所有数据都绘制在同一个图中。如果需要将离群点单独绘制,可以考虑使用其他的图表类型或者自己对数据进行处理再绘图。
阅读全文