Story telling
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
# Sample data with 'Year' as integers
data = {
'Year': [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2020],
'Population': [2.5, 3.0, 3.7, 4.4, 5.3, 6.1, 6.9, 7.8] # in
billions
}
df = pd.DataFrame(data)
# Convert 'Year' to datetime
df['Year'] = pd.to_datetime(df['Year'], format='%Y')
# Create the line chart with datetime x-axis
fig = px.line(
df,
x='Year',
y='Population',
title='Global Population Growth (1950 - 2020)',
labels={'Population': 'Population (in billions)', 'Year': 'Year'}
)
# Add storytelling annotations
annotations = [
dict(
x=pd.to_datetime('1960'),
y=3.0,
xref='x',
yref='y',
text="Population reaches 3 billion",
showarrow=True,
arrowhead=2
),
dict(
x=pd.to_datetime('1980'),
y=4.4,
xref='x',
yref='y',
text="Rapid growth due to industrialization",
showarrow=True,
arrowhead=2
),
dict(
x=pd.to_datetime('2020'),
y=7.8,
xref='x',
yref='y',
text="Population crosses 7.8 billion",
showarrow=True,
arrowhead=2
)
]
fig.update_layout(annotations=annotations)
# Add interactive range slider with range selector buttons
fig.update_layout(
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=10, label="Last 10 Years", step="year",
stepmode="backward"),
dict(count=20, label="Last 20 Years", step="year",
stepmode="backward"),
dict(step="all")
])
),
rangeslider=dict(visible=True),
type="date" # Ensure the x-axis is treated as dates
)
)
# Add final annotation as a conclusion
fig.add_annotation(
dict(
x=pd.to_datetime('2020'),
y=7.8,
text="What's next for global population growth?",
showarrow=False,
font=dict(size=14, color="red"),
xanchor="center"
)
)
# Display the interactive story
fig.show()
Animation
import plotly.graph_objects as go
import numpy as np
# Create an initial dataset
categories = ['Category A', 'Category B', 'Category C', 'Category D']
data_1 = [50, 70, 30, 90] # Initial values
data_2 = [80, 50, 60, 40] # Updated values (for animation)
# Create the initial figure with bars
fig = go.Figure(data=[go.Bar(x=categories, y=data_1,
marker=dict(color=['#636EFA', '#EF553B', '#00CC96', '#AB63FA']))])
# Add animation frames (smooth transition from data_1 to data_2)
frames = [go.Frame(data=[go.Bar(x=categories, y=np.array(data_1)*(1 -
i/20) + np.array(data_2)*(i/20),
marker=dict(color=['#636EFA',
'#EF553B', '#00CC96', '#AB63FA']))])
for i in range(21)] # 20 frames for smooth transition
# Set up the layout and animation settings
fig.update_layout(
title='Bar Chart with Smooth Transitions',
xaxis_title='Categories',
yaxis_title='Values',
updatemenus=[dict(type='buttons', showactive=False,
buttons=[dict(label='Play', method='animate',
args=[None,
dict(frame=dict(duration=100, redraw=True),
fromcurrent=True)])])])
# Define the frames for animation
fig.frames = frames
# Add slider to control animation
fig.update_layout(sliders=[{
'steps': [{'method': 'animate', 'args': [[f.name], {'frame':
{'duration': 100, 'redraw': True}, 'mode': 'immediate'}],
'label': f'{i}'} for i, f in enumerate(fig.frames)],
'currentvalue': {'prefix': 'Frame: '}
}])
fig.show()
Altair package- statistical visualization
import altair as alt
import pandas as pd
import numpy as np
# Generate sample data
data = pd.DataFrame({
'values': np.random.randn(1000) # 1000 random values from a normal
distribution
})
# Histogram with Binning
chart = alt.Chart(data).mark_bar().encode(
alt.X('values', bin=True), # Apply binning
y='count()' # Count the number of occurrences in each bin
).properties(
title='Histogram with Binned Values'
)
# Display the chart
chart
import altair as alt
import pandas as pd
# Sample Data with subcategories
data = pd.DataFrame({
'category': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'],
'subcategory': ['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'],
'value': [50, 60, 70, 65, 30, 35, 90, 85]
})
# Faceted Bar Chart
chart = alt.Chart(data).mark_bar().encode(
x='subcategory',
y='value',
column='category' # Facet by category
).properties(
title='Faceted Bar Chart'
)
# Display the chart
chart
import altair as alt
import pandas as pd
# Sample Data
data = pd.DataFrame({
'category': ['A', 'B', 'C', 'D'],
'value': [50, 70, 30, 90]
})
# Interactive Bar Chart with Tooltip
chart = alt.Chart(data).mark_bar().encode(
x='category',
y='value',
tooltip=['category', 'value'] # Adding tooltips to the bars
).properties(
title='Interactive Bar Chart'
).interactive() # Makes the chart zoomable and pannable
# Display the chart
chart
import altair as alt
import pandas as pd
# Sample Data
data = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [3, 4, 2, 5, 6]
})
# Create a scatter plot
scatter = alt.Chart(data).mark_point().encode(
x='x',
y='y'
)
# Add a regression line
regression = scatter.transform_regression('x',
'y').mark_line(color='red')
# Combine scatter plot and regression line
chart = scatter + regression
# Display the chart
chart
Dynamic charts
import plotly.express as px
import pandas as pd
# Sample data
df = pd.DataFrame({
"Year": [2018, 2019, 2020, 2021, 2022],
"Sales": [150, 200, 300, 250, 400],
"Profit": [30, 50, 80, 60, 100]
})
# Convert "Year" to a datetime format
df['Year'] = pd.to_datetime(df['Year'], format='%Y')
# Create a dynamic line chart
fig = px.line(df, x="Year", y="Sales", title="Yearly Sales with Dynamic
Interaction")
# Add interactive elements like a range slider
fig.update_layout(
xaxis=dict(
rangeselector=dict(
buttons=list([
dict(count=1, label="1Y", step="year",
stepmode="backward"),
dict(count=2, label="2Y", step="year",
stepmode="backward"),
dict(step="all")
])
),
rangeslider=dict(visible=True),
)
)
fig.show()
Dynamic maps
import folium
# Create a map centered around Madurai
m = folium.Map(location=[9.9252, 78.1198], zoom_start=13)
# Add a marker for the Meenakshi Amman Temple
folium.Marker(
location=[9.9195, 78.1190],
popup="Meenakshi Amman Temple",
icon=folium.Icon(icon="cloud"),
).add_to(m)
# Add another marker for Madurai Junction Railway Station
folium.Marker(
location=[9.9192, 78.1214],
popup="Madurai Junction Railway Station",
icon=folium.Icon(color="red"),
).add_to(m)
# Add a circle marker for Thirumalai Nayakkar Mahal
folium.CircleMarker(
location=[9.9196, 78.1283],
radius=50,
popup="Thirumalai Nayakkar Mahal",
color="#3186cc",
fill=True,
fill_color="#3186cc",
).add_to(m)
# Display the map
m
Animation types -2D
import plotly.express as px
import pandas as pd
import numpy as np
# Create a dataset
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
df = pd.DataFrame({'x': x, 'y': y})
# Create an animated line chart
fig = px.line(df, x='x', y='y', title="2D Animated Line Chart")
# Adding frames for animation
frames = [px.line(df.iloc[:i], x='x', y='y') for i in range(1,
len(df))]
# Show animation
fig.show()
Animation types -3D
import plotly.graph_objects as go
import numpy as np
# Create a dataset
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
# Create a surface plot
fig = go.Figure(data=[go.Surface(z=z, x=x, y=y)])
# Add animation to rotate the surface plot
frames = [go.Frame(data=[go.Surface(z=z, x=x, y=y)],
layout=dict(scene=dict(camera=dict(eye=dict(x=np.cos(t), y=np.sin(t),
z=0.5))))) for t in np.linspace(0, 2*np.pi, 30)]
fig.frames = frames
# Add buttons and sliders for the animation
fig.update_layout(
updatemenus=[dict(type='buttons', showactive=False,
buttons=[dict(label='Play', method='animate',
args=[None])])])
fig.show()