You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于日期与时间的Python时间序列分析可视化方案问询

Got it, let's tackle this critical business need for time series visualization that shows both date and time dimensions. Your existing histogram and line chart code are great starting points—here's how to enhance them to meet your requirement:

1. First: Prep Your Data for Date + Time Analysis

Before we dive into visuals, we need to combine date and time into a single datetime column (assuming your dataset has separate date and time fields) and set it as the index for easier time-series operations:

import pandas as pd
import matplotlib.pyplot as plt

# Load your dataset (adjust the read method to match your file type)
df = pd.read_csv("your_dataset_file.csv")

# Merge date and time into a single datetime column
df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
# Set datetime as the index for time-series functions
df.set_index('datetime', inplace=True)

2. Enhanced Histogram: Show Distribution by Date + Time Intervals

Your original histogram only groups by date—let's modify it to show counts across specific time intervals (like hours, 15-minute blocks, etc.) so you can see daily patterns alongside dates:

def time_based_histogram(df, freq='H'):
    # Use 'H' for hourly, '15T' for 15-minute intervals, 'D' for original daily view
    time_grouped = df.resample(freq).size()
    
    plt.figure(figsize=(17, 5), edgecolor='blue')
    time_grouped.plot(kind='bar', color='#86bf91', grid=False)
    plt.title(f'Data Distribution by {freq} Intervals')
    plt.xlabel('Datetime (Date + Time)')
    plt.ylabel('Number of Records')
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()

# Example: Plot hourly distribution across all dates
time_based_histogram(df, freq='H')

This histogram will have x-axis labels that include both date and time, so you can spot trends like "peak records every weekday at 9 AM".

3. Refined Line Chart: Track Sentiment Across Date + Time

Your existing line chart aggregates by date—let's update it to show sentiment trends at a finer time granularity, so you can see hourly (or smaller) changes within each day:

def detailed_time_series_plot(df, y_col='sentiment', freq='H', title='Sentiment Over Date & Time'):
    # Resample data to your desired time interval and sum sentiment values
    resampled_data = df[y_col].resample(freq).sum()
    
    plt.figure(figsize=(16, 5), dpi=100)
    plt.plot(resampled_data.index, resampled_data.values, color='tab:red')
    plt.gca().set(title=title, xlabel='Datetime (Date + Time)', ylabel=y_col)
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()

# Example: Plot hourly sentiment trends
detailed_time_series_plot(df, freq='H')

Now you can see exactly when sentiment spikes or dips throughout the day, not just overall daily totals.

4. Combined Visualization: Histogram + Line Chart (Dual Axis)

For a more powerful business-focused view, combine both metrics (record count and sentiment) into one chart—this lets you correlate volume with sentiment performance across date and time:

def combined_time_visualization(df, freq='H'):
    # Aggregate both count and sentiment data by time interval
    count_data = df.resample(freq).size()
    sentiment_data = df['sentiment'].resample(freq).sum()
    
    fig, ax1 = plt.subplots(figsize=(17, 5), dpi=100)
    
    # Left axis: Bar chart for record counts
    ax1.bar(count_data.index, count_data.values, color='#86bf91', alpha=0.6)
    ax1.set_xlabel('Datetime (Date + Time)')
    ax1.set_ylabel('Record Count', color='#86bf91')
    ax1.tick_params(axis='y', labelcolor='#86bf91')
    ax1.set_title('Record Count & Sentiment Over Date + Time')
    
    # Right axis: Line chart for sentiment
    ax2 = ax1.twinx()
    ax2.plot(sentiment_data.index, sentiment_data.values, color='tab:red', linewidth=2)
    ax2.set_ylabel('Total Sentiment', color='tab:red')
    ax2.tick_params(axis='y', labelcolor='tab:red')
    
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.show()

# Example: View hourly count and sentiment together
combined_time_visualization(df, freq='H')

This is perfect for identifying patterns like "high volume at 10 AM but low sentiment—need to investigate that hour".

5. Bonus: Interactive Visualization (For Exploration)

If you need a more flexible tool for deep dives (like zooming into a specific day or hovering to see exact values), use Plotly for interactive charts:

import plotly.express as px
import plotly.graph_objects as go

def interactive_time_plot(df, freq='H'):
    # Aggregate data into a flat dataframe for Plotly
    resampled_df = df.resample(freq).agg(
        total_sentiment=('sentiment', 'sum'),
        record_count=('sentiment', 'size')
    ).reset_index()
    
    fig = go.Figure()
    # Add bar chart for record counts
    fig.add_trace(go.Bar(
        x=resampled_df['datetime'],
        y=resampled_df['record_count'],
        name='Record Count',
        marker_color='#86bf91'
    ))
    # Add line chart for sentiment (on secondary axis)
    fig.add_trace(go.Scatter(
        x=resampled_df['datetime'],
        y=resampled_df['total_sentiment'],
        name='Total Sentiment',
        yaxis='y2',
        line_color='tab:red'
    ))
    
    # Update layout for clarity and interactivity
    fig.update_layout(
        title='Record Count & Sentiment Over Date + Time',
        xaxis_title='Datetime',
        yaxis_title='Record Count',
        yaxis2=dict(title='Total Sentiment', overlaying='y', side='right'),
        width=1200,
        height=500,
        xaxis_tickangle=-45
    )
    fig.show()

# Example: Launch interactive chart
interactive_time_plot(df, freq='H')

内容的提问来源于stack exchange,提问作者Nurdin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:57:52