import sys
from typing import Any, Dict, List, Union
import plotly.express as px
from datasets import DatasetDict, load_dataset
from datasets import Dataset
import pandas as pd
def load_and_convert_dataset(dataset_name: str, split: str = "train") -> pd.DataFrame:
"""
Load a dataset using the Hugging Face `datasets` library and convert it to a pandas DataFrame.
Args:
dataset_name (str): The name of the dataset to load.
split (str): The split of the dataset to load (e.g., 'train', 'test').
Returns:
pd.DataFrame: The loaded dataset as a pandas DataFrame.
Raises:
ValueError: If the specified split does not exist in the dataset.
Exception: For any other exceptions during dataset loading.
"""
try:
dataset_dict: DatasetDict = load_dataset(dataset_name)
if split not in dataset_dict:
raise ValueError(f"Split '{split}' not found in the dataset. Available splits: {list(dataset_dict.keys())}")
dataset: Dataset = dataset_dict[split]
df: pd.DataFrame = dataset.to_pandas()
return df
except Exception as e:
print(f"Error loading dataset '{dataset_name}': {e}", file=sys.stderr)
raise
def identify_column_types(df: pd.DataFrame) -> Dict[str, str]:
"""
Identify the data type of each column in the DataFrame.
Args:
df (pd.DataFrame): The DataFrame to analyze.
Returns:
Dict[str, str]: A dictionary mapping column names to their identified types ('categorical', 'numerical', 'text').
"""
column_types: Dict[str, str] = {}
for column in df.columns:
if pd.api.types.is_numeric_dtype(df[column]):
column_types[column] = "numerical"
elif pd.api.types.is_string_dtype(df[column]):
# Heuristic: If average string length is greater than a threshold, consider it as text
avg_length = df[column].dropna().astype(str).map(len).mean()
column_types[column] = "text" if avg_length > 20 else "categorical"
else:
column_types[column] = "categorical"
return column_types
def plot_categorical_column(df: pd.DataFrame, column: str) -> None:
"""
Plot a bar chart for a categorical column showing the count of each category.
Args:
df (pd.DataFrame): The DataFrame containing the data.
column (str): The name of the categorical column to plot.
"""
try:
fig = px.bar(
df[column].value_counts().reset_index(),
x='index',
y=column,
labels={'index': column, column: 'Count'},
title=f'Distribution of {column}',
)
fig.show()
except Exception as e:
print(f"Error plotting categorical column '{column}': {e}", file=sys.stderr)
def plot_numerical_column(df: pd.DataFrame, column: str) -> None:
"""
Plot a histogram for a numerical column showing its distribution.
Args:
df (pd.DataFrame): The DataFrame containing the data.
column (str): The name of the numerical column to plot.
"""
try:
fig = px.histogram(
df,
x=column,
nbins=30,
title=f'Distribution of {column}',
labels={column: column},
)
fig.show()
except Exception as e:
print(f"Error plotting numerical column '{column}': {e}", file=sys.stderr)
def plot_text_column_length(df: pd.DataFrame, column: str) -> None:
"""
Plot a histogram of text length for a text column.
Args:
df (pd.DataFrame): The DataFrame containing the data.
column (str): The name of the text column to analyze.
"""
try:
text_lengths = df[column].dropna().astype(str).map(len)
fig = px.histogram(
text_lengths,
x=text_lengths,
nbins=30,
title=f'Length Distribution of {column}',
labels={'x': 'Text Length', 'count': 'Frequency'},
)
fig.show()
except Exception as e:
print(f"Error plotting text column '{column}': {e}", file=sys.stderr)
def plot_pairwise_relationships(df: pd.DataFrame, column_types: Dict[str, str]) -> None:
"""
Plot pairwise relationships between columns based on their types.
Args:
df (pd.DataFrame): The DataFrame containing the data.
column_types (Dict[str, str]): A dictionary mapping column names to their types.
"""
numerical_columns: List[str] = [col for col, typ in column_types.items() if typ == "numerical"]
categorical_columns: List[str] = [col for col, typ in column_types.items() if typ == "categorical"]
# Scatter plots for numerical-numerical
for i in range(len(numerical_columns)):
for j in range(i + 1, len(numerical_columns)):
col_x = numerical_columns[i]
col_y = numerical_columns[j]
try:
fig = px.scatter(
df,
x=col_x,
y=col_y,
title=f'Scatter Plot of {col_x} vs {col_y}',
labels={col_x: col_x, col_y: col_y},
)
fig.show()
except Exception as e:
print(f"Error plotting scatter between '{col_x}' and '{col_y}': {e}", file=sys.stderr)
# Box plots for numerical vs categorical
for num_col in numerical_columns:
for cat_col in categorical_columns:
try:
fig = px.box(
df,
x=cat_col,
y=num_col,
title=f'Box Plot of {num_col} by {cat_col}',
labels={cat_col: cat_col, num_col: num_col},
)
fig.show()
except Exception as e:
print(f"Error plotting box plot of '{num_col}' by '{cat_col}': {e}", file=sys.stderr)
def visualize_dataset(dataset_name: str, split: str = "train") -> None:
"""
Load a dataset and generate visualizations based on its structure.
Args:
dataset_name (str): The name of the dataset to load.
split (str): The split of the dataset to visualize.
"""
try:
df: pd.DataFrame = load_and_convert_dataset(dataset_name, split)
print(f"Dataset '{dataset_name}' loaded successfully with {len(df)} rows and {len(df.columns)} columns.")
except Exception:
return
column_types: Dict[str, str] = identify_column_types(df)
print(f"Identified column types: {column_types}")
for column, col_type in column_types.items():
if col_type == "categorical":
plot_categorical_column(df, column)
elif col_type == "numerical":
plot_numerical_column(df, column)
elif col_type == "text":
plot_text_column_length(df, column)
else:
print(f"Unknown column type for '{column}': {col_type}", file=sys.stderr)
plot_pairwise_relationships(df, column_types)
if __name__ == "__main__":
DATASET_NAME: str = "fka/awesome-chatgpt-prompts"
SPLIT: str = "train"
visualize_dataset(DATASET_NAME, SPLIT)
Explanation
The provided Python script is a comprehensive, reusable, and generalized solution for visualizing datasets using the Plotly library. It adheres strictly to PEP-8 standards, includes type hints for enhanced clarity and maintainability, and incorporates robust error handling to ensure resilience against unexpected issues.
Key Components:
-
Data Loading and Conversion:
- The
load_and_convert_dataset function utilizes the datasets library to load a specified dataset and converts it into a pandas DataFrame for easier manipulation and visualization.
-
Column Type Identification:
- The
identify_column_types function analyzes each column in the DataFrame to determine whether it's numerical, categorical, or textual. This classification is crucial for selecting the appropriate type of visualization.
-
Visualization Functions:
- Categorical Data:
plot_categorical_column generates bar charts showcasing the distribution of categories within a column.
- Numerical Data:
plot_numerical_column creates histograms to display the distribution of numerical values.
- Textual Data:
plot_text_column_length visualizes the distribution of text lengths, providing insights into the variability and size of text entries.
- Pairwise Relationships:
plot_pairwise_relationships explores relationships between different columns, generating scatter plots for numerical-numerical pairs and box plots for numerical-categorical pairs.
-
Main Visualization Workflow:
- The
visualize_dataset function orchestrates the entire process:
- It loads the dataset and converts it to a DataFrame.
- Identifies the types of each column.
- Iteratively generates appropriate visualizations for each column based on its type.
- Examines and plots pairwise relationships between columns to uncover deeper insights.
-
Execution Entry Point:
- The script is designed to run as a standalone module. When executed, it loads the
"fka/awesome-chatgpt-prompts" dataset (specifically the train split) and generates a series of interactive Plotly visualizations.
Robustness and Reusability:
-
Error Handling: Each function includes try-except blocks to gracefully handle potential errors, such as issues with data loading or plotting. Meaningful error messages are printed to stderr to aid in troubleshooting.
-
Generality: The script does not hard-code any dataset-specific parameters, making it easily adaptable to a wide range of datasets with varying structures and types.
-
Type Hints and Documentation: Comprehensive type annotations and docstrings enhance the readability and maintainability of the code, facilitating easier updates and scalability.
Usage:
To use this script with a different dataset, simply modify the DATASET_NAME and SPLIT variables in the __main__ section. Ensure that the desired dataset is available through the Hugging Face datasets library.
if __name__ == "__main__":
DATASET_NAME: str = "your-dataset-name"
SPLIT: str = "desired-split" # e.g., 'train', 'test'
visualize_dataset(DATASET_NAME, SPLIT)
This structure ensures that the visualization tool is both powerful and flexible, capable of handling diverse datasets and providing meaningful insights through clear and interactive visual representations.