4

私はパンダと非matplotlibのプロットを試しています。良い提案はここにあります。この質問はyhat の ggplotに関するもので、2 つの問題が発生しています。パンダでシリーズをプロットするのは簡単です。

frequ.plot()

ggplot ドキュメントでこれを行う方法がわかりません。代わりに、データフレームを作成することになります:

cheese = DataFrame({'time': frequ.index, 'count' : frequ.values})
ggplot(cheese, aes(x='time', y='count')) + geom_line()

「パンダとの緊密な統合」を持つプロジェクトであるggplotには、単純なシリーズをプロットする方法があると思います。

2 番目の問題は、x 軸が時刻の場合に stat_smooth() を表示できないことです。この投稿に関連しているようですが、そこに投稿する担当者がいません。私のコードは次のとおりです。

frequ = values.sampler.resample("1Min", how="count")
cheese = DataFrame({'time': frequ.index, 'count' : frequ.values})
ggplot(cheese, aes(x='time', y='count')) + geom_line() + stat_smooth()

matplotlib 以外のプロットに関するヘルプをいただければ幸いです。ありがとう!(私はggplot 0.5.8を使用しています)

4

2 に答える 2

10

複数の株価と経済時系列を扱うとき、Python の ggplot でこの問題に頻繁に遭遇します。ggplot で覚えておくべき重要な点は、問題を回避するために、データは長い形式で編成するのが最適であるということです。回避策として、簡単な 2 ステップのプロセスを使用します。まず、株価データを取得しましょう。

import pandas.io.data as web
import pandas as pd
import time
from ggplot import *

stocks = [ 'GOOG', 'MSFT', 'LNKD', 'YHOO', 'FB', 'GOOGL','HPQ','AMZN'] # stock list

# get stock price function #
def get_px(stock, start, end):
    return web.get_data_yahoo(stock, start, end)['Adj Close']

# dataframe of equity prices   
px = pd.DataFrame({n: get_px(n, '1/1/2014', date_today) for n in stocks})

px.head()
              AMZN     FB  GOOG   GOOGL    HPQ    LNKD   MSFT   YHOO
Date                                                                
2014-01-02  397.97  54.71   NaN  557.12  27.40  207.64  36.63  39.59
2014-01-03  396.44  54.56   NaN  553.05  28.07  207.42  36.38  40.12
2014-01-06  393.63  57.20   NaN  559.22  28.02  203.92  35.61  39.93
2014-01-07  398.03  57.92   NaN  570.00  27.91  209.64  35.89  40.92
2014-01-08  401.92  58.23   NaN  571.19  27.19  209.06  35.25  41.02

最初に、ワイド フォーマットからロング フォーマットに切り替えるときに正しくプロットするために、ggplot では日時インデックスを pandas データフレームの列にする必要があることを理解してください。この特定の点に対処する関数を作成しました。pandas シリーズのインデックスから type=datetime の「Date」列を作成するだけです。

def dateConvert(df):
  df['Date'] = df.index
  df.reset_index(drop=True)
  return df

そこから、df で関数を実行します。「Date」を id_vars として使用して、結果を pandas pd.melt のオブジェクトとして使用します。返された df は、標準の ggplot() 形式を使用してプロットする準備ができました。

px_returns = px.pct_change() # common stock transformation
cumRet = (1+px_returns).cumprod() - 1 # transform daily returns to cumulative 
cumRet_dateConverted = dateConvert(cumRet) # run the function here see the result below#

cumRet_dateConverted.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 118 entries, 2014-01-02 00:00:00 to 2014-06-20 00:00:00
Data columns (total 9 columns):
AMZN     117 non-null float64
FB       117 non-null float64
GOOG     59 non-null float64
GOOGL    117 non-null float64
HPQ      117 non-null float64
LNKD     117 non-null float64
MSFT     117 non-null float64
YHOO     117 non-null float64
Date     118 non-null datetime64[ns]
dtypes: datetime64[ns](1), float64(8)


data = pd.melt(cumRet_dateConverted, id_vars='Date').dropna() # Here is the method I use to format the data in the long format. Please note the use of 'Date' as the id_vars.

data = data.rename(columns = {'Date':'Date','variable':'Stocks','value':'Returns'}) # common to rename these columns

ここから、必要に応じてデータをプロットできます。私が使用する一般的なプロットは次のとおりです。

retPlot_YTD = ggplot(data, aes('Date','Returns',color='Stocks')) \
+ geom_line(size=2.) \
+ geom_hline(yintercept=0, color='black', size=1.7, linetype='-.') \
+ scale_y_continuous(labels='percent') \
+ scale_x_date(labels='%b %d %y',breaks=date_breaks('week') ) \
+ theme_seaborn(style='whitegrid') \
+ ggtitle(('%s Cumulative Daily Return vs Peers_YTD') % key_Stock) 

fig = retPlot_YTD.draw()
ax = fig.axes[0]
offbox = ax.artists[0]
offbox.set_bbox_to_anchor((1, 0.5), ax.transAxes)
fig.show()

ggplot を使用した FB cumRet プロット

于 2014-06-23T20:42:45.503 に答える
8

これは回避策ですがqplot、シリーズを使用して簡単なプロットをすばやく作成するために使用できます。

from ggplot import *
qplot(meat.beef)
于 2014-05-12T21:53:03.343 に答える