熊猫dataframe plot():x轴日期标签显示但不显示数据

时间:2020-08-26 23:47:19

标签: python pandas matplotlib datetime64

我试图从熊猫数据框中绘制数据作为时间(年)的函数。数据摘要如下所示:

           DATE    WALCL
0    2010-08-18  2313662
1    2010-08-25  2301015
2    2010-09-01  2301996
3    2010-09-08  2305802
4    2010-09-15  2296079
517  2020-07-15  6958604
518  2020-07-22  6964755
519  2020-07-29  6949032
520  2020-08-05  6945237
521  2020-08-12  6957277

我尝试使用以下代码绘制数据:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

dfData = pd.read_csv(sPathIn+sFname, skiprows = 0)

ax = dfData.plot()
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(years_fmt)
ax.xaxis.set_minor_locator(months)
datemin = np.datetime64(dfData['DATE'][0], 'Y')
datemax = np.datetime64(dfData['DATE'].iloc[-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim( datemin, datemax)     
plt.show()

运行此代码时,可以正确显示绘图轴,但不会显示时间序列数据(WALCL)。

enter image description here

如果我省略ax.set_xlim( datemin, datemax),则会显示时间序列数据,但x轴的格式不再正确(从1970年开始,一直运行到1971年)。

enter image description here

这是修改后的代码示例:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
years_fmt = mdates.DateFormatter('%Y')

sPathIn = "C:\\Users\\reg\\projects\\notes\\Political_Economy\\S&P+Fed-Assets\\"
sFname = "WALCL.csv"

这是回溯:

Traceback (most recent call last):

  File "C:\Users\reg\projects\Notes\Political_Economy\S&P+Fed-Assets\Python\s&p-fed-assets-v0.2.3.py", line 25, in <module>
    dfData.set_index('DATE', inplace=True)

  File "C:\Users\reg\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4545, in set_index
    raise KeyError(f"None of {missing} are in the columns")

KeyError: "None of ['DATE'] are in the columns"
    # load data
    dfData = pd.read_csv(sPathIn+sFname, skiprows = 0, parse_dates=['DATE'], index_col='DATE')
    
    #set up plot fxn
    dfData.set_index('DATE', inplace=True)
    ax = dfData.plot('DATE', 'WALCL')
    
    # format the ticks
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(years_fmt)
    ax.xaxis.set_minor_locator(months)
    
    datemin = np.datetime64(dfData['DATE'][0], 'Y')
    datemax = np.datetime64(dfData['DATE'].iloc[-1], 'Y') + np.timedelta64(1, 'Y')
    ax.set_xlim( datemin, datemax)   
    plt.show()

1 个答案:

答案 0 :(得分:2)

  • 数据集位于Assets: Total Assets: Total Assets (Less Eliminations from Consolidation): Wednesday Level (WALCL)
  • 通过将 Public Sub priceList() Dim request As HttpWebRequest Dim response As HttpWebResponse = Nothing Dim reader As StreamReader Dim priceURL As String = "https://www.coinbase.com/api/v2/assets/prices?base=EUR&filter=listed&resolution=latest" Try request = DirectCast(WebRequest.Create(priceURL), HttpWebRequest) request.Timeout = 5000 response = DirectCast(request.GetResponse(), HttpWebResponse) reader = New StreamReader(response.GetResponseStream()) Dim rawresp As String rawresp = reader.ReadToEnd() Dim jobjRes As JObject = JObject.Parse(rawresp) lblBTC.Text = jobjRes("data")("prices")("latest") 'to get the value `9681.37187377` lblETH.Text = jobjRes("data")("latest")(1) 'to get the value `327.19364587` Catch ex As Exception End Try End Sub { "data": [ { "base": "BTC", "base_id": "5b71fc48-3dd3-540c-809b-f8c94d0e68b5", "unit_price_scale": 2, "currency": "EUR", "prices": { "latest": "9681.37187377", "latest_price": { "amount": { "amount": "9681.37187377", "currency": "EUR", "scale": "2" }, "timestamp": "2020-08-26T22:25:34+00:00", "percent_change": { "hour": -0.0039851372378422469, "day": 0.005259534656113684, "week": -0.03463919031166367, "month": 0.16049643434894343, "year": 0.03693469348569537 } } } }, { "base": "BCH", "base_id": "45f99e13-b522-57d7-8058-c57bf92fe7a3", "unit_price_scale": 2, "currency": "EUR", "prices": { "latest": "232.73798095", "latest_price": { "amount": { "amount": "232.73798095", "currency": "EUR", "scale": "2" }, "timestamp": "2020-08-26T22:25:34+00:00", "percent_change": { "hour": -0.004045444134858329, "day": -0.0018292642153924589, "week": -0.0848976489206936, "month": 0.08154645174032256, "year": -0.16691849178508787 } } } }, { "base": "BSV", "base_id": "3512a0ee-b6a5-59ab-b739-5707dc0f7255", "unit_price_scale": 2, "currency": "EUR", "prices": { "latest": "162.25632672453829", "latest_price": { "amount": { "amount": "162.25632672453829", "currency": "EUR", "scale": "2" }, "timestamp": "2020-08-26T22:25:34+00:00", "percent_change": { "hour": -0.005775958074358671, "day": 0.007400135568471085, "week": -0.11560039401936326, "month": -0.006537321045348497, "year": 0.36627211198530926 } } } }, { "base": "ETH", "base_id": "d85dce9b-5b73-5c3c-8978-522ce1d1c1b4", "unit_price_scale": 2, "currency": "EUR", "prices": { "latest": "327.19364587", "latest_price": { "amount": { "amount": "327.19364587", "currency": "EUR", "scale": "2" }, "timestamp": "2020-08-26T22:25:34+00:00", "percent_change": { "hour": -0.009570537282694364, "day": 0.007075834487002035, "week": -0.07595908986415874, "month": 0.24640450219039285, "year": 0.9279573735784573 } } } } ] 一起使用来验证Hotel_id Month_Year last_review_date 2400614 May-2015 March-2016 2400614 June-2015 March-2016 2400614 December-2015 March-2016 2400614 January-2016 March-2016 2400614 March-2016 March-2016 2400133 April-2016 May-2017 2400133 June-2016 May-2017 2400133 August-2016 May-2017 2400133 January-2017 May-2017 2400133 April-2017 May-2017 2400133 May-2017 May-2017 2400178 June-2015 April-2018 2400178 July-2016 April-2018 2400178 August-2016 April-2018 2400178 January-2017 April-2018 2400178 March-2017 April-2018 2400178 April-2018 April-2018 列是否为日期时间格式。

DATE设置为索引

parse_dates

enter image description here

.read_csv保留为列

DATE

enter image description here