python项目:MySQL中有一个goods_train表,表里面有id、date、price。如何读取goods_train表中的date和price数据并生成echarts柱状图
时间: 2023-12-03 12:43:37 浏览: 33
首先,需要使用 Python 中的 MySQL 驱动程序来连接到 MySQL 数据库。我推荐使用 PyMySQL 驱动程序,可以使用 pip 命令进行安装。
安装 PyMySQL:
```
pip install PyMySQL
```
连接到 MySQL 数据库并读取数据:
```python
import pymysql
# 连接到 MySQL 数据库
connection = pymysql.connect(host='localhost',
user='root',
password='password',
db='database_name')
# 读取数据
cursor = connection.cursor()
cursor.execute("SELECT date, price FROM goods_train")
data = cursor.fetchall()
# 关闭数据库连接
connection.close()
```
接下来,使用 Echarts 模块来生成柱状图。安装 Echarts:
```
pip install pyecharts
```
生成柱状图代码如下:
```python
from pyecharts.charts import Bar
from pyecharts import options as opts
# 获取 date 和 price 数据
dates = [d[0] for d in data]
prices = [d[1] for d in data]
# 创建柱状图
bar = Bar()
# 添加 x 轴和 y 轴数据
bar.add_xaxis(dates)
bar.add_yaxis("Price", prices)
# 设置全局参数
bar.set_global_opts(title_opts=opts.TitleOpts(title="Goods Price"),
xaxis_opts=opts.AxisOpts(name="Date"),
yaxis_opts=opts.AxisOpts(name="Price"))
# 显示图像
bar.render("goods_price.html")
```
以上代码将数据保存在 `goods_price.html` 文件中,并在浏览器中打开此文件以查看生成的柱状图。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)