plt.subplots 设置日期格式
时间: 2023-11-14 17:08:47 浏览: 38
可以使用 matplotlib 中的 DateFormatter 模块来设置日期格式。具体实现方法如下:
```python
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig, ax = plt.subplots()
# 假设 x 轴是日期数据
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
```
其中,`%Y` 表示年份,`%m` 表示月份,`%d` 表示日期。你可以根据需要自定义日期格式。
相关问题
def fun1(data): data = pd.read_csv(data) data['date_time'] = pd.to_datetime(data['date_time']) plt.figure(figsize=(14, 5)) plt.subplot(1, 2, 1) plt.subplots_adjust(wspace=0.2) # 小提琴图 sns.violinplot(x="year", y="Global_active_power", data=data) plt.xlabel('Year') plt.title('Violin plot of Yearly Global Active Power') sns.despine(left=True, bottom=True) plt.tight_layout() plt.subplot(1, 2, 2) sns.violinplot(x="quarter", y="Global_active_power", data=data) plt.xlabel('Quarter') plt.title('Violin plot of Quarterly Global Active Power') sns.despine(left=True, bottom=True) plt.tight_layout() plt.show()
这段代码使用Python中的pandas和seaborn库,绘制了一个关于年份和季节的全球活跃功率的小提琴图。
首先,通过`pd.read_csv()`函数读取了一个数据集,并将其中的日期时间列转换成了pandas中的日期时间格式。然后,使用`plt.subplots()`函数创建了一个大小为14x5的Figure,并在其中创建了一个大小为1x2的subplot。其中,`plt.subplots_adjust()`函数用于调整子图之间的间距。
在第一个子图中,使用`sns.violinplot()`函数绘制了年份与全球活跃功率之间的小提琴图,并使用`plt.xlabel()`和`plt.title()`函数添加了x轴标签和标题。在第二个子图中,同样使用`sns.violinplot()`函数绘制了季节与全球活跃功率之间的小提琴图,并添加了相应的标签和标题。
最后,使用`sns.despine()`函数去除了图形中的边框线,并使用`plt.tight_layout()`函数调整子图之间的间距,使得图形更加美观。最后,使用`plt.show()`函数显示了整个图形。
请优化这段代码,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()
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函数,使得代码更易读。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)