Python 視覚化アーティファクト
altair
今日は、 r の ggplot に構文が似ているPython ライブラリを紹介します。
中国語との互換性も非常に優れており、簡単な散布図を例に挙げます。
インストールに関するメモ:
pip install altair pip install vega-datasets#注意这里是"-"不是"_",我们要使用到其中的数据
import altair as alt
from vega_datasets import data
cars = data.cars()
cars
alt.Chart(cars).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin',
shape='Origin'
).interactive()
次のグラフィックを出力し、その横にある 3 つの点をクリックして、さまざまな形式の画像として保存します。
その構文は非常に単純であることがわかります。
-
車は私たちが必要とするデータであり、彼はデータフレームです(データフレームの形式)
-
メイクポイントは散布図です
-
x='Horsepower'、y='Miles_per_Gallon' は、それぞれ x 軸と y 軸のデータに対応します。
-
color='Origin' は原点に従って色をマッピングします。これは ggplot の構文と非常によく似ています。
-
shape='Origin'、ここでは原点の場所に従って点の形状をマッピングします。
-
interactive() インタラクティブな画像を生成します。効果は次のとおりです。
1. 簡単なグラフィックをいくつか描きます
(1).ヒストグラム
構文は簡単です
import altair as alt
import pandas as pd
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
alt.Chart(source).mark_bar().encode(
x='a',
y='b',
color="a"
)
1. 次に、強調表示されたヒストグラムの特定の列を設定し、他の列を同じ色に設定することもできます。
import altair as alt
import pandas as pd
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
alt.Chart(source).mark_bar().encode(
x='a:O',
y='b:Q',
color=alt.condition(
alt.datum.a=="A",#这里设置条件,如果a的值是"A",需要改动的只有a这个地方和"A"这个地方,后者是前者满足的条件
alt.value("red"),#如果满足上面的条件颜色就变成红色
alt.value("yellow")#如果不满足就变成黄色
)
).properties(width=600,height=400)#这里的height和width分别设置图片的大小和高度
2. 画像を反転し、同時に画像の注釈を追加し、画像にデータを追加します
えーっと、実際、画像を反転すると、X 軸と Y 軸のデータが入れ替わることになります。
import altair as alt
import pandas as pd
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
bars= alt.Chart(source).mark_bar().encode(
x='b:Q',
y='a:O',
color="a")
text = bars.mark_text(
align='right',#在这里选择一个['left', 'center', 'right']
baseline='middle',
dx=10 # Nudges text to right so it doesn't appear on top of the bar
).encode(
text='a'#这里是添加数据
)
bars+text
3. グラフに線を追加する
import altair as alt
import pandas as pd
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
bars= alt.Chart(source).mark_bar().encode(
x='a',
y='b',
color="a")
rule = alt.Chart(source).mark_rule(color='red').encode(
y='mean(b)',
)
(bars+rule).properties(width=600,height=400)
4. 複合チャート、ヒストグラム + 折れ線チャート
まず、X 軸を修正する必要があります
import altair as alt
from vega_datasets import data
import pandas as pd
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
base = alt.Chart(source).encode(x='a:O')
bar = base.mark_bar().encode(y='b:Q')
line = base.mark_line(color='red').encode(
y='b:Q'
)
(bar + line).properties(width=600)
(2). ヒートマップ
import altair as alt
import numpy as np
import pandas as pd
# Compute x^2 + y^2 across a 2D grid
x, y = np.meshgrid(range(-5, 5), range(-5, 5))
z = x ** 2 + y ** 2
# Convert this grid to columnar data expected by Altair
source = pd.DataFrame({
'x': x.ravel(),
'y': y.ravel(),
'z': z.ravel()})
alt.Chart(source).mark_rect().encode(
x='x:O',
y='y:O',
color='z:Q'
)
(3). ヒストグラム
さまざまな範囲の数値の出現数を数えます
以下は初期の自動車データの例です。
import altair as alt
from vega_datasets import data
cars = data.cars()
cars
alt.Chart(cars).mark_bar().encode(
alt.X("Displacement", bin=True),
y='count()',
color="Origin"
)
(4). 折れ線グラフ
関数曲線の描画に使用できます。例:
y = sin x 5 \displaystyle y=\frac{\sin x}{5}y=5罪×
import altair as alt
import numpy as np
import pandas as pd
x = np.arange(100)
source = pd.DataFrame({
'x': x,
'f(x)': np.sin(x / 5)
})
alt.Chart(source).mark_line().encode(
x='x',
y='f(x)'
)
(5). マウスチップによる散布図
つまり、特定の場所をクリックすると、その座標などの対応する情報が表示されます。
たとえば、次のコードでツールチップを設定し、特定の点をクリックすると、対応する名前、属性、馬力が表示されます。
import altair as alt
from vega_datasets import data
source = data.cars()
alt.Chart(source).mark_circle(size=60).encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin',
tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']
).interactive()
(6). 積み上げ面グラフ
たとえば、次のコードでは、x は異なる年、y は異なる原材料を使用した正味発電量です。
import altair as alt
from vega_datasets import data
source = data.iowa_electricity()
source
alt.Chart(source).mark_area().encode(
x="year:T",
y="net_generation:Q",
color="source:N"
)
(7). ファンチャート
import pandas as pd
import altair as alt
source = pd.DataFrame({
"category": [1, 2, 3, 4, 5, 6], "value": [4, 6, 10, 3, 7, 8]})
alt.Chart(source).mark_arc(innerRadius=50).encode(
theta=alt.Theta(field="value", type="quantitative"),
color=alt.Color(field="category", type="nominal"),
)
2. 高度な操作
1. 折れ線グラフ
1. 95% 信頼区間バンドを含む折れ線グラフを作成します。
## 带有置信区间
import altair as alt
from vega_datasets import data
source = data.cars()
line = alt.Chart(source).mark_line().encode(
x='Year',
y='mean(Miles_per_Gallon)'
)
band = alt.Chart(source).mark_errorband(extent='ci').encode(
x='Year',
y=alt.Y('Miles_per_Gallon', title='Miles/Gallon'),
)
band + line
2. 折れ線グラフのマーカー
#折线图标记
import altair as alt
import numpy as np
import pandas as pd
x = np.arange(100)
source = pd.DataFrame({
'x': x,
'f(x)': np.sin(x / 5)
})
alt.Chart(source).mark_line(
point=alt.OverlayMarkDef(color="red")
).encode(
x='x',
y='f(x)'
)
3. 折れ線グラフの線の太さをさまざまな位置に設定します
#线条粗细随之变化
import altair as alt
from vega_datasets import data
source = data.wheat()
alt.Chart(source).mark_trail().encode(
x='year:T',
y='wheat:Q',
size='wheat:Q'
)
2. 標準エリア積み上げチャート
違うのは、彼が全体像を埋めるということだ
import altair as alt
from vega_datasets import data
source = data.iowa_electricity()
alt.Chart(source).mark_area().encode(
x="year:T",
y=alt.Y("net_generation:Q", stack="normalize"),
color="source:N"
)
3. 隙間のある円グラフ
import numpy as np
import altair as alt
alt.Chart().mark_arc(color="gold").encode(
theta=alt.datum((5 / 8) * np.pi, scale=None),
theta2=alt.datum((19 / 8) * np.pi),
radius=alt.datum(100, scale=None),
)
1.円グラフ
import pandas as pd
import altair as alt
source = pd.DataFrame({
"category": [1, 2, 3, 4, 5, 6], "value": [4, 6, 10, 3, 7, 8]})
alt.Chart(source).mark_arc().encode(
theta=alt.Theta(field="value", type="quantitative"),
color=alt.Color(field="category", type="nominal"),
)
2. 放射円グラフ
import pandas as pd
import altair as alt
source = pd.DataFrame({
"values": [12, 23, 47, 6, 52, 19]})
base = alt.Chart(source).encode(
theta=alt.Theta("values:Q", stack=True),
radius=alt.Radius("values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)),
color="values:N",
)
c1 = base.mark_arc(innerRadius=20, stroke="#fff")
c2 = base.mark_text(radiusOffset=10).encode(text="values:Q")
c1 + c2
4. 高度な散布図
1. エラーバー付きの散布図
import altair as alt
import pandas as pd
import numpy as np
# generate some data points with uncertainties
np.random.seed(0)
x = [1, 2, 3, 4, 5]
y = np.random.normal(10, 0.5, size=len(x))
yerr = 0.2
# set up data frame
source = pd.DataFrame({
"x": x, "y": y, "yerr": yerr})
# the base chart
base = alt.Chart(source).transform_calculate(
ymin="datum.y-datum.yerr",
ymax="datum.y+datum.yerr"
)
# generate the points
points = base.mark_point(
filled=True,
size=50,
color='black'
).encode(
x=alt.X('x', scale=alt.Scale(domain=(0, 6))),
y=alt.Y('y', scale=alt.Scale(zero=False))
)
# generate the error bars
errorbars = base.mark_errorbar().encode(
x="x",
y="ymin:Q",
y2="ymax:Q"
)
points + errorbars
2. 散布図のラベル付け
#散点图加标签
import altair as alt
import pandas as pd
source = pd.DataFrame({
'x': [1, 3, 5, 7, 9],
'y': [1, 3, 5, 7, 9],
'label': ['我', '是', '你', '爸', '爸']
})
points = alt.Chart(source).mark_point().encode(
x='x:Q',
y='y:Q'
)
text = points.mark_text(
align='left',
baseline='middle',
dx=7
).encode(
text='label'
)
points + text
5.世界地図
import altair as alt
from vega_datasets import data
# Data generators for the background
sphere = alt.sphere()
graticule = alt.graticule()
# Source of land data
source = alt.topo_feature(data.world_110m.url, 'countries')
# Layering and configuring the components
alt.layer(
alt.Chart(sphere).mark_geoshape(fill='lightblue'),
alt.Chart(graticule).mark_geoshape(stroke='white', strokeWidth=0.5),
alt.Chart(source).mark_geoshape(fill='ForestGreen', stroke='black')
).project(
'naturalEarth1'
).properties(width=600, height=400).configure_view(stroke=None)
3. 画像を保存する
svg,png,html,pdf,json
次のような形式で保存できます
import altair as alt
from vega_datasets import data
chart = alt.Chart(data.cars.url).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color='Origin:N'
)
chart.save('chart.json')
chart.save('chart.html')
chart.save('chart.png')
chart.save('chart.svg')
chart.save('chart.pdf')
保存する画像のサイズも設定します
chart.save('chart.png', scale_factor=2.0)
4. 画像の一部のプロパティの設定
たとえば、画像にタイトルを追加します。
#世界地图
import altair as alt
from vega_datasets import data
# Data generators for the background
sphere = alt.sphere()
graticule = alt.graticule()
# Source of land data
source = alt.topo_feature(data.world_110m.url, 'countries')
# Layering and configuring the components
alt.layer(
alt.Chart(sphere).mark_geoshape(fill='lightblue'),
alt.Chart(graticule).mark_geoshape(stroke='white', strokeWidth=0.5),
alt.Chart(source).mark_geoshape(fill='ForestGreen', stroke='black')
).project(
'naturalEarth1'
).properties(width=600, height=400,title="世界地图").configure_view(stroke=None)
財産 | タイプ | 説明 |
---|---|---|
アーク | RectConfig |
Arc 固有の構成 |
エリア | AreaConfig |
エリア固有の構成 |
アリア | boolean |
ARIA のデフォルト属性をマークとガイドに含めるかどうかを示すブール フラグ (SVG 出力のみ)。false の場合、"aria-hidden" 属性はすべてのガイドに設定され、ARIA アクセシビリティ ツリーから削除され、Vega-Lite はマークのデフォルトの説明を生成しません。デフォルト値: true 。 |
自動サイズ変更 | anyOf( AutosizeType , AutoSizeParams ) |
視覚化のサイズを決定する方法。文字列の場合は、 、"pad" 、"fit" のいずれかにする必要があります"none" 。オブジェクト値では、コンテンツのサイズ変更と自動サイズ変更のパラメーターをさらに指定できます。デフォルト値:pad |
軸 | AxisConfig |
軸構成。 allx およびy axesのデフォルトのプロパティを決定します。軸構成オプションの完全なリストについては、軸のドキュメントの対応するセクションを参照してください。 |
軸バンド | AxisConfig |
「バンド」スケールを持つ軸を設定します。 |
軸下 | AxisConfig |
グラフの下端に沿って X 軸を設定します。 |
軸離散 | AxisConfig |
「ポイント」スケールまたは「バンド」スケールを使用して軸を構成します。 |
軸左 | AxisConfig |
チャートの左端に沿って Y 軸を設定します。 |
軸点 | AxisConfig |
「ポイント」スケールを持つ軸を構成します。 |
軸定量的 | AxisConfig |
定量軸の設定。 |
右軸 | AxisConfig |
チャートの右端に沿って Y 軸を設定します。 |
時間軸 | AxisConfig |
時間軸の設定。 |
軸上 | AxisConfig |
グラフの上端に沿って X 軸を設定します。 |
軸X | AxisConfig |
X 軸固有の構成。 |
軸Xバンド | AxisConfig |
「バンド」スケールを使用して X 軸を構成します。 |
軸X離散 | AxisConfig |
「ポイント」スケールまたは「バンド」スケールを使用して X 軸を構成します。 |
軸X点 | AxisConfig |
「ポイント」スケールを使用して X 軸を構成します。 |
軸X定量的 | AxisConfig |
X 定量軸の構成。 |
軸X時間 | AxisConfig |
X 時間軸の構成。 |
Y軸 | AxisConfig |
Y軸固有の構成。 |
軸Yバンド | AxisConfig |
「バンド」スケールを使用して Y 軸を構成します。 |
軸Y離散 | AxisConfig |
「ポイント」または「バンド」スケールを使用して y 軸を構成します。 |
軸Y点 | AxisConfig |
「ポイント」スケールを使用して y 軸を構成します。 |
軸Y定量的 | AxisConfig |
y 定量軸の構成。 |
軸Y時間 | AxisConfig |
y 時間軸の構成。 |
バックグラウンド | anyOf( Color , ExprRef ) |
ビュー全体の背景として使用する CSS カラー プロパティ。デフォルト値: "white" |
バー | BarConfig |
Bar-Specific Config |
boxplot | BoxPlotConfig |
Box Config |
circle | MarkConfig |
Circle-Specific Config |
concat | CompositionConfig |
Default configuration for all concatenation and repeat view composition operators (concat , hconcat , vconcat , and repeat ) |
countTitle | string |
Default axis and legend title for count fields.Default value: 'Count of Records . |
customFormatTypes | boolean |
Allow the formatType property for text marks and guides to accept a custom formatter function registered as a Vega expression. |
errorband | ErrorBandConfig |
ErrorBand Config |
errorbar | ErrorBarConfig |
ErrorBar Config |
facet | CompositionConfig |
Default configuration for the facet view composition operator |
fieldTitle | [‘verbal’, ‘functional’, ‘plain’] | Defines how Vega-Lite generates title for fields. There are three possible styles: - "verbal" (Default) - displays function in a verbal style (e.g., “Sum of field”, “Year-month of date”, “field (binned)”). - "function" - displays function using parentheses and capitalized texts (e.g., “SUM(field)”, “YEARMONTH(date)”, “BIN(field)”). - "plain" - displays only the field name without functions (e.g., “field”, “date”, “field”). |
font | string |
Default font for all text marks, titles, and labels. |
geoshape | MarkConfig |
Geoshape-Specific Config |
header | HeaderConfig |
Header configuration, which determines default properties for all headers.For a full list of header configuration options, please see the corresponding section of in the header documentation. |
headerColumn | HeaderConfig |
Header configuration, which determines default properties for column headers.For a full list of header configuration options, please see the corresponding section of in the header documentation. |
headerFacet | HeaderConfig |
Header configuration, which determines default properties for non-row/column facet headers.For a full list of header configuration options, please see the corresponding section of in the header documentation. |
headerRow | HeaderConfig |
Header configuration, which determines default properties for row headers.For a full list of header configuration options, please see the corresponding section of in the header documentation. |
image | RectConfig |
Image-specific Config |
legend | LegendConfig |
Legend configuration, which determines default properties for all legends. For a full list of legend configuration options, please see the corresponding section of in the legend documentation. |
line | LineConfig |
Line-Specific Config |
lineBreak | anyOf(string , ExprRef ) |
A delimiter, such as a newline character, upon which to break text strings into multiple lines. This property provides a global default for text marks, which is overridden by mark or style config settings, and by the lineBreak mark encoding channel. If signal-valued, either string or regular expression (regexp) values are valid. |
mark | MarkConfig |
Mark Config |
numberFormat | string |
D3 Number format for guide labels and text marks. For example "s" for SI units. Use D3’s number format pattern. |
padding | anyOf(Padding , ExprRef ) |
The default visualization padding, in pixels, from the edge of the visualization canvas to the data rectangle. If a number, specifies padding for all sides. If an object, the value should have the format {"left": 5, "top": 5, "right": 5, "bottom": 5} to specify padding for each side of the visualization.Default value: 5 |
params | array(Parameter ) |
Dynamic variables that parameterize a visualization. |
point | MarkConfig |
Point-Specific Config |
projection | ProjectionConfig |
Projection configuration, which determines default properties for all projections. For a full list of projection configuration options, please see the corresponding section of the projection documentation. |
range | RangeConfig |
An object hash that defines default range arrays or schemes for using with scales. For a full list of scale range configuration options, please see the corresponding section of the scale documentation. |
rect | RectConfig |
Rect-Specific Config |
rule | MarkConfig |
Rule-Specific Config |
scale | ScaleConfig |
Scale configuration determines default properties for all scales. For a full list of scale configuration options, please see the corresponding section of the scale documentation. |
selection | SelectionConfig |
An object hash for defining default properties for each type of selections. |
square | MarkConfig |
Square-Specific Config |
style | StyleConfigIndex |
An object hash that defines key-value mappings to determine default properties for marks with a given style. The keys represent styles names; the values have to be valid mark configuration objects. |
text | MarkConfig |
Text-Specific Config |
tick | TickConfig |
Tick-Specific Config |
timeFormat | string |
Default time format for raw time values (without time units) in text marks, legend labels and header labels.Default value: "%b %d, %Y" Note: Axes automatically determine the format for each label automatically so this config does not affect axes. |
title | TitleConfig |
Title configuration, which determines default properties for all titles. For a full list of title configuration options, please see the corresponding section of the title documentation. |
trail | LineConfig |
Trail-Specific Config |
意見 | ViewConfig |
単一ビュー プロットのデフォルトのプロパティ。 |
長所と短所
長所: 構文が簡単、中国語との互換性が良い、r 言語の ggplot に非常に似ています。
欠点: 生成されたイメージは直接コピーできず、ローカルに保存する必要がありますが、これは matplotlib ほど優れたものではありません
研究に興味がある場合は、このリンクをクリックしてください
いくつかの写真を見せてください
参照: 詳細なコンテンツについては、ここをクリックしてください: https://altair-viz.github.io/gallery/index.html