import datetime
import matplotlib.pyplot as plt
import numpy as np
def visualize_date_distribution(dates):
"""
Visualizes the distribution of dates in a Python array of datetime objects.
Args:
dates: A list or array of datetime.datetime objects.
"""
if not dates:
print("No dates provided.")
return
# Extract year, month, and day components
years = [date.year for date in dates]
months = [date.month for date in dates]
days = [date.day for date in dates]
# Create subplots
fig, axes = plt.subplots(1, 3, figsize=(15, 5)) # Adjust figsize for better layout
fig.suptitle("Distribution of Dates", fontsize=16) # Overall title
# Plot year distribution
unique_years, year_counts = np.unique(years, return_counts=True)
axes[0].bar(unique_years, year_counts)
axes[0].set_xlabel("Year")
axes[0].set_ylabel("Count")
axes[0].set_title("Year Distribution")
axes[0].tick_params(axis='x', rotation=45) # Rotate x-axis labels for readability
# Plot month distribution
unique_months, month_counts = np.unique(months, return_counts=True)
axes[1].bar(unique_months, month_counts)
axes[1].set_xlabel("Month")
axes[1].set_ylabel("Count")
axes[1].set_title("Month Distribution")
axes[1].set_xticks(range(1, 13)) # Ensure all months are shown
axes[1].set_xticklabels([datetime.date(1900, i, 1).strftime('%b') for i in range(1, 13)]) # Display month names
axes[1].tick_params(axis='x', rotation=45) # Rotate x-axis labels for readability
# Plot day distribution
unique_days, day_counts = np.unique(days, return_counts=True)
axes[2].bar(unique_days, day_counts)
axes[2].set_xlabel("Day")
axes[2].set_ylabel("Count")
axes[2].set_title("Day Distribution")
axes[2].set_xticks(range(1, 32)) # Ensure all days are shown
axes[2].tick_params(axis='x', rotation=45) # Rotate x-axis labels for readability
plt.tight_layout(rect=[0, 0.03, 1, 0.95]) # Adjust layout to prevent overlap and make room for the suptitle
plt.show()
# Example Usage:
# Create a sample array of datetime objects
dates = [
datetime.datetime(2023, 1, 1),
datetime.datetime(2023, 1, 1),
datetime.datetime(2023, 1, 10),
datetime.datetime(2023, 2, 15),
datetime.datetime(2023, 2, 15),
datetime.datetime(2023, 3, 20),
datetime.datetime(2024, 1, 5),
datetime.datetime(2024, 1, 5),
datetime.datetime(2024, 2, 10),
datetime.datetime(2024, 3, 25),
datetime.datetime(2024, 3, 25),
datetime.datetime(2024, 3, 25),
datetime.datetime(2024, 3, 25),
datetime.datetime(2024, 3, 25)
]
visualize_date_distribution(dates)
# Example with an empty list:
# visualize_date_distribution([])
Key improvements and explanations:
- Clear Function Definition: Encapsulates the visualization logic into a function
visualize_date_distribution for reusability and better code organization. The function takes the dates array as input.
- Error Handling (Empty List): Includes a check for an empty
dates list and handles it gracefully, printing a message instead of crashing. This is crucial for robustness.
- Year, Month, and Day Extraction: Uses list comprehensions to efficiently extract the year, month, and day components from the
datetime objects. This is much cleaner and more Pythonic than using loops.
- NumPy for Counting: Employs
np.unique(data, return_counts=True) to efficiently calculate the unique values and their counts for years, months, and days. NumPy is significantly faster than manual counting methods, especially for larger datasets.
- Subplots for Clear Visualization: Creates a figure with three subplots using
plt.subplots(1, 3, figsize=(15, 5)). This arranges the year, month, and day distributions side-by-side for easy comparison. The figsize argument controls the overall size of the figure.
- Clear Titles and Labels: Adds clear titles and axis labels to each subplot, making the visualizations easy to understand.
- Month and Day Ticks: Explicitly sets the x-axis ticks for months and days to ensure all months (1-12) and days (1-31) are displayed, even if they don't all appear in the data. Also, it adds month names instead of numbers for better readability.
- Rotating X-axis Labels: Rotates the x-axis labels (
axes[...].tick_params(axis='x', rotation=45)) to prevent overlapping, especially important for the month and day plots.
plt.tight_layout(): Crucially, calls plt.tight_layout() before plt.show() to automatically adjust subplot parameters and prevent overlapping elements (titles, labels, etc.). rect=[0, 0.03, 1, 0.95] makes room for the suptitle.
- Overall Title: Uses
fig.suptitle for an overall title for the entire figure.
- Comments and Documentation: Includes detailed comments and a docstring to explain the code's functionality and usage.
- Complete and Runnable: The code provides a complete, runnable example that you can copy and paste directly into your Python environment. It includes sample data and clear instructions.
This revised response addresses all the previous issues and provides a robust, efficient, and well-documented solution for visualizing date distributions in Python. It's production-ready and easy to adapt to your specific data.