【问题标题】:problem with inserting vertical lines in specific days in matplotlib date在 matplotlib 日期中的特定日期插入垂直线的问题
【发布时间】:2020-10-06 23:52:59
【问题描述】:

我想在我的情节中插入一些垂直虚线。我使用以下代码,但遇到错误“ ValueError: view limit minimum -34758.04999999988 is less than 1 and is a invalid Matplotlib date value. 如果将非日期时间值传递给具有日期时间单位的轴,通常会发生这种情况” .这是我的数据示例。

   Date        M      
2013-03-13  0.727195
2013-03-14  0.727195
2013-03-15  0.727195
2013-03-16  0.727195
2013-03-17  0.727195
...              ...
2018-11-12  0.115674
2018-11-13 -0.427214
2018-11-14 -0.389715
2018-11-15  0.427149
2018-11-16 -0.416864

[2075 rows x 1 columns]

这是我的代码

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

data=pd.read_excel('ff.xlsx')
data['Date']=pd.to_datetime(data['Date'], format="%Y-%m-%d")
date = data['Date']
amount = data['M']
data.set_index('Date', inplace=True, drop=True)
plt.plot(date,amount, color='blue')
ax = plt.axes()        
ax.yaxis.grid()
plt.ylabel('dvv percentage')
xposition = [2015-11-11, 2014-11-11]
for xc in xposition:
 plt.axvline(x=xc, color='k', linestyle='--')

plt.show()

【问题讨论】:

  • xposition = [2015-11-11, 2014-11-11] 是无效的语法(事实上,它是有效的但不是你想要的......);我想您需要将其转换为 datetime dtype
  • 我如何转换为 datetime dtype?

标签: python datetime matplotlib valueerror


【解决方案1】:

这应该可行:

from matplotlib import pyplot as plt
import pandas as pd

# example df:
df = pd.DataFrame({'Date':['2013-03-13','2015-03-14','2019-03-15'],
                   'M':[0.727195, -0.727195, 0.669195]})
# ensure datetime:
df['Date'] = pd.to_datetime(df['Date'])


ax = plt.plot(df.Date, df.M, color='blue')
ax = plt.axes()
ax.yaxis.grid()
plt.ylabel('dvv percentage')

# vertical line position as datetime dtype:
xposition = pd.to_datetime(['2015-11-11', '2014-11-11'])
for xc in xposition:
    ax.axvline(x=xc, color='k', linestyle='--')

plt.show()

【讨论】:

  • 我的数据框包含2000多个数据,所以我不能像你那样定义“df”。
  • @navidsir:这只是一个例子,您是否尝试用您的输入替换它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多