generated at
Altair

altair.py
import altair as alt alt.Chart(df).mark_point().encode( x="date:T", y="value" )

なんかいいサンプル

Q , O , N , T , G
mark_* シリーズ
複数の系列を描画する
縦持ちなら素直に color="item:N"
facet="item:N" で item ごとにグラフを分けて書ける
.resolve_scale(y='independent') で軸を別々にできる、指定しない場合は共通の高さ
transform_fold で複数のカラムを指定したら value という名前に束縛される
(たぶん) カラム名が key に入っているので color="key:N" などするとよい
N は nominal、ラベル変数に使う
alt.Chart(df).transform_fold(["price", "users"]).mark_line.encode(..., y="value:Q")

インタラクティブなグラフ
ツールチップ出す
encode(..., tooltip=['col1', 'col2'])
ズーム可能に
.interactive()
ダブルクリックでズームリセットできる
複数の系列で出すのはかなりだるい、ホバーした x 軸にいい感じに出るやつ簡単になってほしい
transform_fold , transform_pivot

複数のグラフを並べる
a | b で横に
a & b で縦に並べる

properties
alt.Chart(...).mark_hoge(...).encode(...).properties() で指定するやつ
title
width
mark_bar(width=10) は bar の幅、グラフのサイズは properties

線の順序
積み上げ棒グラフで順序を指定したいときなど
.encode(..., order=alt.Order('field', sort="ascending")) など


TypeError: Object of type 'date' is not JSON serializable の回避
alt.Chart(df) に渡す DataFrame 中に date datetime など JSON 化できないオブジェクトが含まれていると起きる(グラフ定義で参照していなくても内部で JSON 化されエラーになる)
alt.Chart(df[['dt', 'key', 'value']]) のように描画に必要なカラムだけ選択した DataFrame を渡すのが楽

グラフのサイズをでかくする
alt.Chart(width=..., height=...) で設定できる
.encode(...).properties(width=1000, height=500) メソッドチェーンで後置するための .properties もある

index を使う
単に index の値をそのまま x 軸などで連番で表示したい場合、Altair は index を描画に使えない
reset_index() を呼ぶと使える
alt.Chart(df.reset_index()).mark_plot().encode(x="index", ...)

軸ごとの範囲
軸に alt.Scale で渡す
x=alt.X("percentage:Q", scale=alt.Scale(domain=[0, 100]))

日付や時刻の binning
encode(alt.X("yearmonthdate(dt):T"), ...)
year-month-date の bin にいれる、よく使う
encode(alt.X("hours(dt):T"), ...)
0-23時(hour)のbinに入れる
hours_minutes もある
day で曜日が取れる
hours yearmonth 等に対して utc prefix のついた utchours utcyearmonth もある
Local(Single|Multi)TimeUnit に対して UTC(Single|Multi)TimeUnit
これを使って x,y 別々の bin に入れて x="monthdate(dt):O", y="hours(dt):O", color="count():Q" するのもオツである

ツールチップの時刻のフォーマットが気に食わない
.encode(..., tooltip=[alt.Tooltip("...", formatType="time", format="%Y-%m-%dT%H:%M")]

左右で別々の軸にしたい
.resolve_scale(y='independent') を使う
複数の Chart を alt.layer でくっつけて軸を独立させるのが楽
resolve_scale_layer.py
a = alt.Chart(...).mark_line(color='orange').encode(...) b = alt.Chart(...).mark_line(color='steelblue').encode(...) alt.layer(a, b).resolve_scale(y='independent')

encode
取れる値いろいろありすぎる
y="sum(value):Q" みたいなのは省略表記
y={"aggregate": "sum", "field": "value", "type": "quantitative"} の意

複数の値のツールチップ
これが参考になる!!

しかし tooltip を多数の動的な値にするには
columns = sorted(source.symbol.unique()) しておいて
encode(..., tooltip=[alt.Tooltip(c, type='quantitative') for c in columns]) などするとよい
よいけど、columns が多すぎるとまともに見れない、そのポイントにあるデータだけほしい

labelAngle
日付などラベルの傾きを指定する
.encode(x=alt.X("yearmonth(date):T", axis=alt.Axis(title="month", format="%Y-%m", labelAngle=-90)), ...)

MaxRows
alt.data_transformers.disable_max_rows() で無効にできる


pd.melt
複数系列のグラフを書きたい時のグループ化に使える、 value , variable に値が束縛される

DataFrame の加工
積み重ねグラフなど、こういう加工をしたいときがある
df
from revenue profit 2020-06-01 100 10 2020-06-02 200 20 2020-06-03 300 30 to date label value 0 2020-06-01 revenue 100 1 2020-06-01 profit 10 2 2020-06-02 revenue 200 3 2020-06-02 profit 20 4 2020-06-03 revenue 300 5 2020-06-03 profit 30

df.reset_index() で日付を index ではなくする
いいアイディアはなくて、ちまちまと加工するしかない?
pivot / unpivot?