pandas 我如何排序日期并在matplotlib的x轴上只显示月+年?

alen0pnh  于 2023-01-01  发布在  其他
关注(0)|答案(2)|浏览(228)

我想改进我的比特币数据集,但我发现日期的排序方式不正确,只想显示月份和年份。我该怎么做?

data = Bitcoin_Historical['Price']
Date1 = Bitcoin_Historical['Date']
train1 = Bitcoin_Historical[['Date','Price']]
#Setting the Date as Index
train2 = train1.set_index('Date')
train2.sort_index(inplace=True)
cols = ['Price']
train2 = train2[cols].apply(lambda x: pd.to_numeric(x.astype(str)
                     .str.replace(',',''), errors='coerce'))
print (type(train2))
print (train2.head())

plt.figure(figsize=(15, 5))
plt.plot(train2)
plt.xlabel('Date', fontsize=12)
plt.xlim(0,20)
plt.ylabel('Price', fontsize=12)
plt.title("Closing price distribution of bitcoin", fontsize=15)
plt.gcf().autofmt_xdate()
plt.show()

结果如下图所示:

它没有排序,显示所有日期。我想按月+年排序,只显示月份名称+年。怎么做?
数据示例:

谢谢

vuktfyat

vuktfyat1#

试着将“Date”列转换为datetime,检查它是否起作用:

train1.Date = pd.to_datetime(train1.Date)
train2 = train1.set_index('Date')
iih3973s

iih3973s2#

我对您的代码进行了以下编辑:

  • 已将列Date转换为日期时间类型
  • 清理Price列并转换为float
  • 删除了导致输出到显示器1970的plt.xlim(0,20)
  • 我使用了替代的方式来绘图,使x轴可以格式化,以获得每月刻度线,更多信息here

请尝试以下代码:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
pd.options.mode.chained_assignment = None

Bitcoin_Historical = pd.read_csv('data.csv')
train1 = Bitcoin_Historical[['Date','Price']]
train1['Date'] = pd.to_datetime(train1['Date'], infer_datetime_format=True, errors='coerce')
train1['Price'] = train1['Price'].str.replace(',','').str.replace(' ','').astype(float)
train2 = train1.set_index('Date')    #Setting the Date as Index
train2.sort_index(inplace=True)

print (type(train2))
print (train2.head())

ax = train2.plot(figsize=(15, 5))
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
plt.xlabel('Date', fontsize=12)
plt.ylabel('Price', fontsize=12)
plt.title("Closing price distribution of bitcoin", fontsize=15)
plt.show()

产出

相关问题