Skip to content

Instantly share code, notes, and snippets.

@iwasa-kosui
Last active January 13, 2019 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwasa-kosui/fca7bb99950db5ebf00cfa337f902d0d to your computer and use it in GitHub Desktop.
Save iwasa-kosui/fca7bb99950db5ebf00cfa337f902d0d to your computer and use it in GitHub Desktop.
Altair 3分チュートリアル

インストール

$ brew tap homebrew/cask
$ brew cask install chromedriver
$ pip install altair selenium pandas

折れ線グラフを表示する

Amazon, IBM, Google, Apple の銘柄ごとの株価をグラフ化

import altair as alt
import pandas as pd

# Amazon, IBM, Google, Apple の銘柄ごとの株価
stock_prices = pd.DataFrame(
    [
        ["AMZN", "2003-01-01", 21.85],
        ["AMZN", "2004-01-01", 50.4],
        ["AMZN", "2005-01-01", 43.22],
        ["AMZN", "2006-01-01", 44.82],
        ["AMZN", "2007-01-01", 37.67],
        ["AMZN", "2008-01-01", 77.7],
        ["IBM", "2003-01-01", 71.22],
        ["IBM", "2004-01-01", 91.06],
        ["IBM", "2005-01-01", 86.39],
        ["IBM", "2006-01-01", 75.89],
        ["IBM", "2007-01-01", 93.79],
        ["IBM", "2008-01-01", 102.75],
        ["GOOG", "2005-01-01", 195.62],
        ["GOOG", "2006-01-01", 432.66],
        ["GOOG", "2007-01-01", 501.5],
        ["GOOG", "2008-01-01", 564.3],
        ["AAPL", "2000-01-01", 25.94],
        ["AAPL", "2003-01-01", 7.18],
        ["AAPL", "2004-01-01", 11.28],
        ["AAPL", "2005-01-01", 38.45],
        ["AAPL", "2006-01-01", 75.51],
        ["AAPL", "2007-01-01", 85.73],
        ["AAPL", "2008-01-01", 135.36],
    ],
    columns=("stock", "date", "price")
)

# 折れ線グラフを作成する
chart = alt.Chart(stock_prices).mark_line().encode(
    x='date',
    y='price',
    color='stock',
).properties(width=500, height=300) # 幅と高さは指定しなくてもよい

# 保存する
chart.save("chart.png")

https://i.imgur.com/QTqnE9i.png

見た目をカスタマイズする

chart = alt.Chart(stock_prices).mark_line().encode(
    x='date',
    y=alt.Y(
        'price',
        # scaleは表示範囲をコントロールする (https://altair-viz.github.io/user_guide/generated/core/altair.Scale.html)
        scale=alt.Scale(
            domain=(0, 300),  # yの表示範囲を200から600にする
            clamp=True,  # False:はみ出た部分を表示する, True:はみ出た部分を表示しない,
        ),
        # axisは軸をコントロールする (https://altair-viz.github.io/user_guide/generated/core/altair.Axis.html)
        axis=alt.Axis( 
            tickCount=20, # y軸の刻みを20ずつにする
            title="価格", # y軸のタイトルを「価格」にする
        )),
    color='stock'
).properties(width=640, height=240)

chart.save("chart.png")

https://i.imgur.com/aVTvSrs.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment