繁体   English   中英

如何排序日期并在 matplotlib 中的 x 轴上仅显示月+年?

[英]How can I order dates and show only month+year on the x axis in matplotlib?

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

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()

结果如下图所示:

结果图像

它未订购并显示所有日期。 我想按月+年排序,只显示月名+年。 那怎么办?

数据示例:

结果图像

谢谢

尝试将您的“日期”列转换为日期时间,检查它是否有效:

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

我对您的代码进行了以下修改:

  • 将列Date列转换为日期时间类型
  • 清理Price列并转换为浮动
  • 删除了导致 output 显示 1970 的行plt.xlim(0,20)
  • 使用 plot 的替代方法,以便可以格式化 x 轴以获得每月刻度线,更多信息在这里

请尝试以下代码:

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()

Output

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM