<jupyter_start><jupyter_text>Getting StartedThis is the basic exercise to familiarise yourself with using altair to create the data visualisations in pythonWe will use the sample data set to create the visualisation  Imports<jupyter_code>import numpy as np
import pandas as pd
import altair as alt<jupyter_output><empty_output><jupyter_text>RenderersTo enable javascript linked rendered for your enviornment, you may need to install a renderer for Altair.- If you are using JupyterLab, you don't need to do anything.- If you are using Jupyter Notebook, you need to enable the notebook renderer.<jupyter_code># For Jupyter Notebook (not JupyterLab) environment
# alt.renderers.enable('notebook')<jupyter_output><empty_output><jupyter_text>DataAltair works on a "long format" Pandas dataframes. Let us get a small sample dataset to work with.<jupyter_code>sample = pd.read_csv("data/sample.csv")
sample.head()
sample.shape<jupyter_output><empty_output><jupyter_text>Visualisation GrammarA basic visualisation in made up of grammar of graphics consists of the atleast the following basic units- **Data**: a pandas DataFrame- **Mark**: Point, Circle, Bar, Line, ...- **Encoding**: X, Y, Color, Size, ...  Chart Object & DataThe basic object in Altair is the Chart, which takes a data frame as a single argument:<jupyter_code>vis = alt.Chart(sample)<jupyter_output><empty_output><jupyter_text>Marks & Encoding Channels*Marks* are the basic geometrical shape we will use to show the data point. For the dataframe, each row will be considered for drawing this shapeSince we have not given any position for the mark, all of them are rendered on top of each other.<jupyter_code>alt.Chart(sample).mark_point()<jupyter_output><empty_output><jupyter_text>Adding the *encoding channels* like positions will start to make the visualisation workLet us add `area` to the Position X channel<jupyter_code>alt.Chart(sample).mark_point().encode(y="area")<jupyter_output><empty_output><jupyter_text>Let us add `sales` to the Position Y channel<jupyter_code>alt.Chart(sample).mark_point().encode(
    y="area",
    x="sales"
)<jupyter_output><empty_output><jupyter_text>We can also use the construction methods for encoding, using the syntax `alt.X(var_name)`<jupyter_code>alt.Chart(sample).mark_point().encode(
    alt.Y("area"),
    alt.X("sales")
)<jupyter_output><empty_output><jupyter_text>The data type for each field is inferred automatically based on its type within the Pandas data frame. We can also explicitly indicate the data type to Altair by annotating the field name: - 'b:N' indicates a nominal type (unordered, categorical data), - 'b:O' indicates an ordinal type (rank-ordered data), - 'b:Q' indicates a quantitative type (numerical data with meaningful magnitudes), and - 'b:T' indicates a temporal type (date/time data)<jupyter_code>alt.Chart(sample).mark_point().encode(
    alt.Y("area:N"),
    alt.X("sales:Q")
)<jupyter_output><empty_output><jupyter_text>MarksMarks can be changed example: bar, circle, point, line, ...<jupyter_code>alt.Chart(sample).mark_bar().encode(
    alt.Y("area:N"),
    alt.X("sales:Q")
)<jupyter_output><empty_output><jupyter_text>Annotations<jupyter_code>alt.Chart(sample).mark_bar(color='firebrick').encode(
  alt.X('sales', axis=alt.Axis(title='Sales in Millions')),
  alt.Y('area', axis=alt.Axis(title='Areas')),
)<jupyter_output><empty_output><jupyter_text>Compositions We can combine multiple views together to compose complex visualsiation using - Facets- Concat Horizontal- Concat Vertical- Layering **Horizontal Concatentation**<jupyter_code>sales_vis = alt.Chart(sample).mark_bar(color='firebrick').encode(
  alt.X('sales', axis=alt.Axis(title='Sales in Millions')),
  alt.Y('area', axis=alt.Axis(title='Areas')),
)

profit_vis = alt.Chart(sample).mark_bar(color='blue').encode(
  alt.X('profit', axis=alt.Axis(title='Profit in Millions')),
  alt.Y('area', axis=alt.Axis(title='Areas')),
)

sales_vis | profit_vis<jupyter_output><empty_output><jupyter_text>**Layering**<jupyter_code>sales_vis = alt.Chart(sample).mark_bar(color='firebrick').encode(
  alt.X('sales', axis=alt.Axis(title='Sales in Millions')),
  alt.Y('area', axis=alt.Axis(title='Areas')),
)

profit_vis = alt.Chart(sample).mark_bar(color='blue').encode(
  alt.X('profit', axis=alt.Axis(title='Profit in Millions')),
  alt.Y('area', axis=alt.Axis(title='Areas')),
)

sales_vis + profit_vis<jupyter_output><empty_output><jupyter_text>InteractivityTo create a simple interactive plot that supports panning and zooming, we can invoke the interactive() method of the Chart object. In the chart below, click and drag to pan or use the scroll wheel to zoom:<jupyter_code>alt.Chart(sample).mark_circle(color='firebrick').encode(
  alt.X('sales', axis=alt.Axis(title='Sales in Millions')),
  alt.Y('profit', axis=alt.Axis(title='Profit in Millions')),
  alt.Size(value=500),
  color="area"
).interactive()<jupyter_output><empty_output><jupyter_text>Vega-lite & AltairAltair is built as an api on top of Vega-Lite - a javascript implementation of the grammar of interactive graphics. Altair converts the plot into a json specification and the Vega-lite render is used to convert it to the graphics.<jupyter_code>chart = alt.Chart(sample).mark_bar().encode(
    x='sales',
    y='area',
)
print(chart.to_json())
x = alt.X('Sales:Q')
print(x.to_json())<jupyter_output>{
  "field": "Sales",
  "type": "quantitative"
}<jupyter_text>Publishing There are many options to use the graphics:- PNG output- SVG output- HTML output- Embed in your applicationHere is an example of saving the chart to html<jupyter_code>chart = alt.Chart(sample).mark_bar().encode(
    x='sales',
    y='area',
)
chart.save('chart.html')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12526168876482904, 'fraction_numerical': 0.00052337752965806, 'mean_word_length': 6.484334203655353, 'pattern_counts': {'":': 2, '<': 64, '<?xml version=': 0, '>': 64, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '218657', 'license': 'MIT', 'n_tokens_mistral': 1899, 'n_tokens_neox': 1844, 'n_words': 521, 'path': '01-Small.ipynb', 'repo_name': 'amitkaps/data-vis-python', 'size': '5732'}