【问题标题】:How do you use matplotlib function fill_between with pandas dataframe如何将 matplotlib 函数 fill_between 与 pandas 数据框一起使用
【发布时间】:2016-04-28 13:35:41
【问题描述】:

我有一个有效的股价折线图,但我想使用函数之间的填充。我尝试直接从系列中传递值并创建列表等,但没有任何效果。这可能吗?

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 读取。非常感谢所有帮助。

【问题讨论】:

    标签: python-3.x pandas matplotlib


    【解决方案1】:
    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' 无法安全地将输入强制转换为任何支持的类型

    如果myDF.indexmyDF['Close'] 是对象数组,则可能发生。举个简单的例子,

    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']) 将日期字符串转换为类似日期时间的对象。

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

    【讨论】:

    • 这看起来很棒,但是,理想情况下,我想通过阅读我自己的 csv 文件来实现相同的目标。这可能吗?谢谢。
    • @teshHi:您发布的使用pd.read_csv 定义myDF 的代码对我来说看起来不错。尝试注释掉以myDF = pdata.get_data_google 开头的行并取消注释上面使用pd.read_csv 定义myDF 的两行。有错误吗?如果是这样,请发布完整的回溯错误消息和 csv 文件示例。
    • Traceback(最近一次调用最后):文件“testFill.py”,第 19 行,在 ax.fill_between(myDF.index, 0, myDF['Close'], alpha=0.3 , label='LON:TSCO') 文件“..\matplotlib_init_.py”,第 1812 行,内部返回 func(ax, *args, **kwargs) 文件“matplotlib\axes_axes. py”,第 4606 行,在 fill_between x = ma.masked_invalid(self.convert_xunits(x)) 文件“..\numpy\ma\core.py”,第 2299 行,在 masked_invalid 条件 = ~(np.isfinite(a) )
    • contd: TypeError: ufunc 'isfinite' 不支持输入类型,并且根据转换规则 ''safe'' 无法安全地将输入强制转换为任何支持的类型
    猜你喜欢
    • 2015-06-02
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 2021-01-01
    • 2016-10-03
    • 2016-10-06
    • 2017-10-23
    相关资源
    最近更新 更多