Code Explanation:
Importing the Altair Library
import altair as alt
What it does:
Imports the Altair library and gives it the short alias alt.
Why:
Altair is a declarative data visualization library for Python — you describe what you want to visualize (not how to draw it). It integrates very well with Pandas dataframes and Vega-Lite under the hood.
Importing the Pandas Library
import pandas as pd
What it does:
Imports the Pandas library with the alias pd.
Why:
Pandas provides powerful data structures like DataFrame — ideal for storing and manipulating tabular data (rows and columns).
Creating a Pandas DataFrame
df = pd.DataFrame({'x':[1,2,3], 'y':[4,5,6]})
What it does:
Creates a small DataFrame with two columns:
'x' = [1, 2, 3]
'y' = [4, 5, 6]
So the DataFrame looks like this:
x y
0 1 4
1 2 5
2 3 6
Why:
This serves as the data source for the chart.
Each row will represent one bar in the bar chart.
Creating an Altair Chart Object
chart = alt.Chart(df).mark_bar().encode(x='x', y='y')
What it does:
alt.Chart(df) creates a Chart object using the DataFrame df as the data source.
.mark_bar() specifies that you want a bar chart (as opposed to points, lines, etc.).
.encode(x='x', y='y') tells Altair how to map data columns to visual elements:
The column 'x' goes on the x-axis.
The column 'y' goes on the y-axis.
Why:
This single line fully defines the bar chart’s structure — Altair takes care of rendering the visualization using Vega-Lite automatically.
Printing the Column Names
print(list(df.columns))
What it does:
df.columns gives an Index object containing the column names (Index(['x', 'y'], dtype='object')).
Wrapping it in list() converts it to a normal Python list.
print() outputs that list to the console.
Output:
['x', 'y']
.png)

0 Comments:
Post a Comment