请优化这段代码,import pandas as pdimport matplotlib.pyplot as plt# 读取csv文件df = pd.read_csv("AAPL.csv")# 将日期列转化为pandas的日期类型df["Date"] = pd.to_datetime(df["Date"])# 设置日期列为数据框的索引df.set_index("Date", inplace=True)# 绘制收盘价折线图plt.plot(df["Close"])plt.title("AAPL Stock Price")plt.xlabel("Date")plt.ylabel("Price")plt.show()# 绘制成交量柱状图plt.bar(df.index, df["Volume"])plt.title("AAPL Stock Volume")plt.xlabel("Date")plt.ylabel("Volume")plt.show()# 绘制K线图from mpl_finance import candlestick_ochlimport matplotlib.dates as mdatesdf_ochl = df[["Open", "Close", "High", "Low"]]df_ochl.reset_index(inplace=True)df_ochl["Date"] = df_ochl["Date"].map(mdates.date2num)fig, ax = plt.subplots()candlestick_ochl(ax, df_ochl.values, width=0.6, colorup="green", colordown="red")ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))plt.title("AAPL Stock Price (Candlestick Chart)")plt.xlabel("Date")plt.ylabel("Price")plt.show()
时间: 2023-07-06 16:25:20 浏览: 160
pandas.read_csv参数详解(小结)
import pandas as pd
import matplotlib.pyplot as plt
from mplfinance.original_flavor import candlestick_ochl
import matplotlib.dates as mdates
# 读取csv文件,并将日期列转化为pandas的日期类型,并将日期列设置为数据框的索引
df = pd.read_csv("AAPL.csv", parse_dates=["Date"], index_col="Date")
# 绘制收盘价折线图
fig, ax1 = plt.subplots()
ax1.plot(df["Close"])
ax1.set_title("AAPL Stock Price")
ax1.set_xlabel("Date")
ax1.set_ylabel("Price")
# 绘制成交量柱状图
ax2 = ax1.twinx()
ax2.bar(df.index, df["Volume"], width=0.5, alpha=0.3)
ax2.set_ylabel("Volume")
# 绘制K线图
fig, ax = plt.subplots()
candlestick_ochl(ax, df[["Open", "Close", "High", "Low"]].values, width=0.5, colorup="green", colordown="red")
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
ax.set_title("AAPL Stock Price (Candlestick Chart)")
ax.set_xlabel("Date")
ax.set_ylabel("Price")
plt.show()
这个版本的代码可以通过将柱状图和折线图放在同一图表上,减少图表数量。此外,我们使用了mplfinance库中的candlestick_ochl函数替代了mpl_finance库中的candlestick_ochl函数,这是因为后者已经被弃用。最后,我们使用了set_xxx和set_yyy函数代替了xlabel,ylabel和title函数,使得代码更易读。
阅读全文