读取csv文件将数据实现可视化,以echarts 库绘制环形图、连续变量的直方图、等弧度玫瑰图和气泡图为例
时间: 2023-12-10 22:40:37 浏览: 195
好的,我来给你讲一下如何使用Python中的pandas库读取csv文件,并使用echarts库绘制环形图、直方图、玫瑰图和气泡图。
首先我们需要安装pandas和echarts库,可以通过以下命令进行安装:
```
pip install pandas
pip install pyecharts
```
接下来,我们需要先读取csv文件中的数据。假设我们的csv文件名为data.csv,包含以下字段:age、gender、income、education、location。代码如下:
```python
import pandas as pd
df = pd.read_csv('data.csv')
```
读取完成后,我们可以使用pandas库对数据进行一些处理,比如筛选出需要的字段、处理缺失值等。
接下来,我们使用echarts库绘制环形图、直方图、玫瑰图和气泡图。
绘制环形图:
```python
from pyecharts import options as opts
from pyecharts.charts import Pie
# 统计各个性别的人数
gender_count = df['gender'].value_counts()
# 绘制环形图
pie = (
Pie()
.add("", [list(z) for z in zip(gender_count.index, gender_count.values)])
.set_colors(["blue", "pink"])
.set_global_opts(
title_opts=opts.TitleOpts(title="Gender Distribution"),
legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
)
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
)
pie.render_notebook()
```
绘制直方图:
```python
from pyecharts import options as opts
from pyecharts.charts import Bar
# 统计收入分布情况
income_count = df['income'].value_counts()
# 绘制直方图
bar = (
Bar()
.add_xaxis(income_count.index.tolist())
.add_yaxis("", income_count.values.tolist())
.set_global_opts(
title_opts=opts.TitleOpts(title="Income Distribution"),
xaxis_opts=opts.AxisOpts(name="Income"),
yaxis_opts=opts.AxisOpts(name="Count"),
)
)
bar.render_notebook()
```
绘制玫瑰图:
```python
from pyecharts import options as opts
from pyecharts.charts import Pie
# 统计教育程度分布情况
edu_count = df['education'].value_counts()
# 绘制玫瑰图
pie = (
Pie()
.add(
"",
[list(z) for z in zip(edu_count.index.tolist(), edu_count.values.tolist())],
radius=["20%", "70%"],
center=["50%", "50%"],
rosetype="radius",
label_opts=opts.LabelOpts(is_show=False),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Education Distribution"),
legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
)
)
pie.render_notebook()
```
绘制气泡图:
```python
from pyecharts import options as opts
from pyecharts.charts import Scatter
# 绘制气泡图
scatter = (
Scatter()
.add_xaxis(df['age'].tolist())
.add_yaxis("", df['income'].tolist())
.set_global_opts(
title_opts=opts.TitleOpts(title="Age vs Income"),
xaxis_opts=opts.AxisOpts(name="Age"),
yaxis_opts=opts.AxisOpts(name="Income"),
)
)
scatter.render_notebook()
```
以上就是如何使用Python的pandas库和echarts库读取csv文件并绘制环形图、直方图、玫瑰图和气泡图的方法。
阅读全文