Introduction
In the wake of Meta's $18 billion settlement with the US Department of Justice, understanding how social media platforms manipulate user behavior has become crucial. This tutorial will teach you how to analyze and visualize user engagement patterns on social media platforms using Python and data visualization libraries. You'll learn to build a tool that can help identify potentially addictive design patterns in social media apps, similar to what the lawsuit alleges about Meta's platforms.
Prerequisites
- Basic Python programming knowledge
- Installed Python 3.8+ environment
- Knowledge of data analysis with pandas
- Understanding of data visualization concepts
- Required Python libraries: pandas, matplotlib, seaborn, numpy
Step-by-Step Instructions
Step 1: Setting Up Your Development Environment
Before we begin analyzing social media data, we need to install and import the necessary libraries. This step ensures we have all the tools required for data manipulation and visualization.
Install Required Libraries
pip install pandas matplotlib seaborn numpy
Import Libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# Set plotting style
plt.style.use('seaborn-v0_8')
sns.set_palette('husl')
Why this matters: These libraries provide the foundation for data analysis and visualization. Pandas handles data manipulation, while matplotlib and seaborn create meaningful visualizations that can reveal patterns in user behavior.
Step 2: Creating Sample Social Media Engagement Data
To demonstrate how to analyze addictive design patterns, we'll create a synthetic dataset that mimics user behavior on social media platforms. This dataset will include metrics like time spent, notifications received, and engagement rates.
Create Sample Dataset
# Create sample social media engagement data
np.random.seed(42)
# Generate data for 1000 users over 30 days
user_ids = range(1000)
days = range(30)
# Create DataFrame
data = []
for user in user_ids:
# User engagement metrics
for day in days:
# Simulate addictive behaviors
time_spent = np.random.normal(45, 15) # Average 45 minutes
notifications = np.random.poisson(5) # Average 5 notifications
likes_received = np.random.poisson(3) # Average 3 likes
comments_received = np.random.poisson(1) # Average 1 comment
# Add some addictive pattern - increased engagement after notifications
if notifications > 3:
time_spent += np.random.normal(10, 5) # Extra time after notifications
data.append({
'user_id': user,
'day': day,
'time_spent_minutes': max(0, time_spent),
'notifications_received': notifications,
'likes_received': likes_received,
'comments_received': comments_received,
'engagement_score': likes_received + comments_received
})
# Convert to DataFrame
df = pd.DataFrame(data)
print(df.head())
Why this matters: This synthetic dataset simulates real user behavior patterns that could indicate addictive design. The correlation between notifications and increased time spent is a key indicator that platforms might be engineered to be addictive.
Step 3: Analyzing Notification-Engagement Correlations
One of the key allegations in the Meta lawsuit involves how platforms are designed to be addictive. We'll analyze how notifications correlate with user engagement to identify potentially problematic patterns.
Calculate Correlation Analysis
# Analyze correlation between notifications and time spent
notification_time_corr = df.groupby('notifications_received')['time_spent_minutes'].mean()
# Create correlation matrix
corr_matrix = df[['time_spent_minutes', 'notifications_received', 'engagement_score']].corr()
print("Average time spent by notification count:")
print(notification_time_corr)
print("\nCorrelation Matrix:")
print(corr_matrix)
Visualize Notification-Engagement Patterns
# Create visualization of notification impact
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
# Plot 1: Time spent vs notifications
sns.scatterplot(data=df, x='notifications_received', y='time_spent_minutes', alpha=0.5, ax=axes[0,0])
axes[0,0].set_title('Time Spent vs Notifications Received')
# Plot 2: Engagement score vs notifications
sns.scatterplot(data=df, x='notifications_received', y='engagement_score', alpha=0.5, ax=axes[0,1])
axes[0,1].set_title('Engagement Score vs Notifications Received')
# Plot 3: Distribution of time spent
sns.histplot(df['time_spent_minutes'], bins=30, ax=axes[1,0])
axes[1,0].set_title('Distribution of Time Spent')
# Plot 4: Correlation heatmap
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0, ax=axes[1,1])
axes[1,1].set_title('Correlation Matrix')
plt.tight_layout()
plt.show()
Why this matters: This analysis helps identify whether platforms are designed to increase user engagement through notification systems, which is a core allegation in the Meta lawsuit. High correlations between notifications and increased time spent suggest addictive design patterns.
Step 4: Identifying Addictive Design Patterns
Now we'll build a more sophisticated analysis to identify specific addictive design patterns that might be present in social media platforms.
Create Addictive Pattern Detection Function
def detect_addictive_patterns(df):
"""Detect potential addictive design patterns in social media data"""
# Calculate average time spent per notification category
df['notification_category'] = pd.cut(df['notifications_received'],
bins=[0, 2, 5, 10, float('inf')],
labels=['Low', 'Moderate', 'High', 'Very High'])
# Group by notification category
pattern_analysis = df.groupby('notification_category').agg({
'time_spent_minutes': ['mean', 'std', 'count'],
'engagement_score': 'mean'
}).round(2)
# Calculate time increase percentage
pattern_analysis['time_increase_percent'] = (
(pattern_analysis[('time_spent_minutes', 'mean')] -
pattern_analysis.loc['Low', ('time_spent_minutes', 'mean')]) /
pattern_analysis.loc['Low', ('time_spent_minutes', 'mean')] * 100
)
return pattern_analysis
# Run pattern detection
addictive_patterns = detect_addictive_patterns(df)
print("Addictive Design Patterns Analysis:")
print(addictive_patterns)
Visualize Addictive Patterns
# Create detailed visualization of addictive patterns
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
# Time spent by notification category
sns.boxplot(data=df, x='notification_category', y='time_spent_minutes', ax=axes[0])
axes[0].set_title('Time Spent by Notification Category')
axes[0].set_xlabel('Notification Level')
# Engagement score by notification category
sns.boxplot(data=df, x='notification_category', y='engagement_score', ax=axes[1])
axes[1].set_title('Engagement Score by Notification Category')
axes[1].set_xlabel('Notification Level')
# Time spent distribution across all users
sns.histplot(df['time_spent_minutes'], bins=50, kde=True, ax=axes[2])
axes[2].set_title('Distribution of Time Spent (All Users)')
axes[2].set_xlabel('Minutes Spent')
plt.tight_layout()
plt.show()
Why this matters: This analysis helps identify specific behavioral patterns that could indicate addictive design. When users spend significantly more time after receiving high numbers of notifications, it suggests platform design is intentionally engineered to keep users engaged.
Step 5: Creating a Dashboard for Monitoring Addictive Patterns
Finally, we'll create a comprehensive dashboard that can help monitor and visualize addictive design patterns in social media platforms.
Build Comprehensive Dashboard
# Create comprehensive dashboard
fig = plt.figure(figsize=(20, 15))
# Subplot 1: Time spent trend
plt.subplot(3, 3, 1)
user_daily_avg = df.groupby(['user_id', 'day'])['time_spent_minutes'].mean().reset_index()
user_daily_avg.groupby('day')['time_spent_minutes'].mean().plot()
plt.title('Average Daily Time Spent')
plt.xlabel('Day')
plt.ylabel('Minutes')
# Subplot 2: Notification frequency
plt.subplot(3, 3, 2)
notification_counts = df['notifications_received'].value_counts().sort_index()
notification_counts.plot(kind='bar')
plt.title('Distribution of Notifications Received')
plt.xlabel('Number of Notifications')
plt.ylabel('Frequency')
# Subplot 3: Time spent vs engagement
plt.subplot(3, 3, 3)
sns.scatterplot(data=df, x='engagement_score', y='time_spent_minutes', alpha=0.5)
plt.title('Time Spent vs Engagement Score')
# Subplot 4: Notification impact over time
plt.subplot(3, 3, 4)
notification_time = df.groupby('notifications_received')['time_spent_minutes'].mean()
notification_time.plot(kind='bar')
plt.title('Average Time Spent by Notification Count')
plt.xlabel('Notifications Received')
plt.ylabel('Average Minutes')
# Subplot 5: User engagement distribution
plt.subplot(3, 3, 5)
sns.histplot(df['engagement_score'], bins=30, kde=True)
plt.title('Distribution of Engagement Scores')
# Subplot 6: Correlation matrix
plt.subplot(3, 3, 6)
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('Feature Correlations')
# Subplot 7: Time spent by user
plt.subplot(3, 3, 7)
user_time = df.groupby('user_id')['time_spent_minutes'].sum().sort_values(ascending=False)
user_time.head(10).plot(kind='bar')
plt.title('Top 10 Users by Total Time Spent')
plt.xlabel('User ID')
plt.ylabel('Total Minutes')
# Subplot 8: Notifications over time
plt.subplot(3, 3, 8)
notification_trend = df.groupby('day')['notifications_received'].mean()
notification_trend.plot()
plt.title('Average Notifications per Day')
plt.xlabel('Day')
plt.ylabel('Average Notifications')
# Subplot 9: Engagement patterns
plt.subplot(3, 3, 9)
engagement_trend = df.groupby('day')['engagement_score'].mean()
engagement_trend.plot()
plt.title('Average Engagement Score Over Time')
plt.xlabel('Day')
plt.ylabel('Average Engagement')
plt.tight_layout()
plt.show()
Why this matters: This comprehensive dashboard provides a holistic view of user behavior patterns that can indicate addictive design. It allows for quick identification of concerning trends and helps in understanding how platform features might be manipulating user behavior.
Summary
This tutorial demonstrated how to analyze social media engagement data to identify potentially addictive design patterns in platforms like Facebook and Instagram. By creating synthetic datasets and analyzing correlations between notifications and user engagement, we've built tools that can help detect the types of behaviors that led to Meta's $18 billion settlement.
The key insights from this analysis include:
- High correlations between notifications and time spent suggest engineered engagement patterns
- Users spend significantly more time after receiving high numbers of notifications
- Platform design appears to be optimized for maximum user engagement
This approach can be adapted to real social media data to conduct more detailed investigations into how platforms might be designed to be addictive, providing valuable insights into the allegations made in the Meta lawsuit.



