数据爬完了,写个图分析看看?
先来个简单的,单独分析一个贵金属的价格在时间坐标轴上的折线图
import pymssql
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'SimHei'
# 连接到SQL Server数据库
conn = pymssql.connect(server='127.0.0.1', user='sa', password='root', database='guijinshu')
showCode = "AuT+D"
# 查询数据
query = "SELECT time, price ,name FROM gold_quote WHERE showCode = '"+showCode+"'"
data = pd.read_sql(query, conn)
# 关闭数据库连接
conn.close()
# 绘制折线图
plt.plot(data['time'], data['price'], marker='o', color='red')
plt.xlabel('时间')
plt.ylabel('价格')
plt.title(data['name'][0]+'的价格与时间折线图: ')
plt.show()
这两天黄金还是在小幅度的涨
接下来我们将指定的五组贵金属放在同一个折线图中
import pymssql
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'SimHei'
# 连接到SQL Server数据库
conn = pymssql.connect(server='127.0.0.1', user='sa', password='root', database='guijinshu')
showCodes = ["AuT+D", "Au9999", "Au9995", "Au100g", "mAuT+D"]
colors = ['red', 'blue', 'green', 'orange', 'purple']
time = '2024-03-25'
for i, showCode in enumerate(showCodes):
# 查询数据
query = "SELECT time, price FROM gold_quote WHERE showCode = '" + showCode + "' and CAST(time AS DATE) > '"+time+"'"
data = pd.read_sql(query, conn)
# 绘制折线图
plt.plot(data['time'], data['price'], marker='o', color=colors[i], label=showCode)
plt.xlabel('时间')
plt.ylabel('价格')
plt.title('多组价格与时间折线图')
plt.legend()
plt.show()
# 关闭数据库连接
conn.close()
再来一个五组分开展示的
import pymssql
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['font.family'] = 'SimHei'
# 连接到SQL Server数据库
conn = pymssql.connect(server='127.0.0.1', user='sa', password='root', database='guijinshu')
showCodes = ["AuT+D", "Au9999", "Au9995", "Au100g", "mAuT+D"]
colors = ['red', 'blue', 'green', 'orange', 'purple']
time = '2024-03-26'
fig, axs = plt.subplots(len(showCodes), 1, figsize=(8, 6 * len(showCodes)))
for i, showCode in enumerate(showCodes):
# 查询数据
query = "SELECT time, price FROM gold_quote WHERE showCode = '" + showCode + "' and CAST(time AS DATE) = '"+time+"'"
data = pd.read_sql(query, conn)
# 绘制折线图
axs[i].plot(data['time'], data['price'], marker='o', color=colors[i], label=showCode)
axs[i].set_xlabel('时间')
axs[i].set_ylabel('价格')
axs[i].set_title('价格与时间折线图 - ' + showCode)
axs[i].legend()
plt.tight_layout()
plt.show()
# 关闭数据库连接
conn.close()