echarts直方图代码前后端
时间: 2023-07-09 15:23:21 浏览: 71
前端代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Echarts 直方图</title>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.2.1/dist/echarts.min.js"></script>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
#chart {
width: 800px;
height: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="chart"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('chart'));
var option = {
title: {
text: '某地区蒸发量和降水量',
subtext: '纯属虚构'
},
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
legend: {
data: ['蒸发量', '降水量']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: {
type: 'value',
boundaryGap: [0, 0.01]
},
yAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
series: [
{
name: '蒸发量',
type: 'bar',
data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6]
},
{
name: '降水量',
type: 'bar',
data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6]
}
]
};
myChart.setOption(option);
</script>
</body>
</html>
```
后端代码示例:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test')
# 获取游标
cursor = conn.cursor()
# 查询数据
sql = "SELECT name, value FROM data"
cursor.execute(sql)
results = cursor.fetchall()
# 处理数据
names = []
values = []
for row in results:
names.append(row[0])
values.append(row[1])
# 关闭连接
cursor.close()
conn.close()
# 生成 Echarts 配置
option = {
'title': {
'text': '某地区蒸发量和降水量',
'subtext': '纯属虚构'
},
'tooltip': {
'trigger': 'axis',
'axisPointer': {
'type': 'shadow'
}
},
'legend': {
'data': ['蒸发量', '降水量']
},
'grid': {
'left': '3%',
'right': '4%',
'bottom': '3%',
'containLabel': True
},
'xAxis': {
'type': 'value',
'boundaryGap': [0, 0.01]
},
'yAxis': {
'type': 'category',
'data': names
},
'series': [
{
'name': '蒸发量',
'type': 'bar',
'data': values
}
]
}
# 返回 Echarts 配置
return option
```
这是一个简单的示例,可以根据实际需求进行修改。前端代码使用 Echarts 库渲染图表,后端代码通过 pymysql 库连接数据库,查询数据并处理成 Echarts 配置格式,最终返回给前端进行渲染。