您如何将 matplotlib 函数 fill_between 与 Pandas 数据框一起使用 [英] How do you use matplotlib function fill_between with pandas dataframe
问题描述
我有一个有效的股票价格折线图,但是我想使用填充功能.我试图直接从系列中传递值,还创建列表等,但没有任何效果.这可能吗?
I have a stock price line graph which works,however I wanted to use the fill between function. I have tried passing in the values directly from the series and also creating lists etc. and nothing works. Is this possible?
myDF = pd.read_csv('C:/Workarea/OneDrive/PyProjects/Learning/stocks_sentdex/GOOG-LON_TSCO.csv')
print(myDF)
myDF = myDF.set_index('Date')
myDF['Close'].plot()
plt.fill_between(?, 0, ?, alpha=0.3)
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Check it out')
plt.legend()
plt.subplots_adjust(left=0.09,bottom=0.16, right=0.94,top=0.90, wspace=0.2, hspace=0)
plt.show()
我见过的所有示例都使用自己的数据或从 urllib 中读取.感谢所有帮助.
All the examples I have seen use their own data or read from a urllib. All help greatly appreciated.
推荐答案
import pandas as pd
import pandas_datareader.data as pdata
import matplotlib.pyplot as plt
# myDF = pd.read_csv('C:/Workarea/OneDrive/PyProjects/Learning/stocks_sentdex/GOOG-LON_TSCO.csv')
# myDF = myDF.set_index('Date')
myDF = pdata.get_data_google('LON:TSCO', start='2009-01-02', end='2009-12-31')
fig, ax = plt.subplots()
ax.fill_between(myDF.index, 0, myDF['Close'], alpha=0.3, label='LON:TSCO')
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.set_title('Check it out')
ax.legend()
fig.subplots_adjust(left=0.09,bottom=0.16, right=0.94,top=0.90, wspace=0.2, hspace=0)
fig.autofmt_xdate()
plt.show()
错误消息
TypeError: ufunc 'isfinite' 不支持输入类型,并且无法根据转换规则 ''safe' 安全地将输入强制转换为任何支持的类型
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'
如果 myDF.index
或 myDF ['Close']
是对象数组,则可能发生
.举个简单的例子
could occur if either myDF.index
or myDF['Close']
is an object array. As a simple example,
In [110]: plt.fill_between(np.array([1,2], dtype='O'), 0, np.array([1,2], dtype='O'))
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
很可能 Date
只是字符串而不是类似日期时间的对象.要解决此问题,请使用 pd.to_datetime(myDF['Date'])
将日期字符串转换为类似日期时间的对象.
Chances are it is the Date
that are mere strings rather than datetime-like objects. To fix this, use pd.to_datetime(myDF['Date'])
to convert the date strings into datetime-like objects.
myDF = pd.read_csv('C:/Workarea/OneDrive/PyProjects/Learning/stocks_sentdex/GOOG-LON_TSCO.csv')
myDF['Date'] = pd.to_datetime(myDF['Date'])
myDF = myDF.set_index('Date')
这篇关于您如何将 matplotlib 函数 fill_between 与 Pandas 数据框一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!