在 Python 中添加另一列作为第二个 X 轴标签

问题描述 投票:0回答:1

我有多个摄像机的 15 分钟间隔时间序列。每个摄像头可以收集 4 条不同腿的 3 种运动类型。每个摄像机都有一个

control_factor
存在一个小时。我想显示每 15 分钟每个摄像机每条腿的计数总数(每个摄像机位于单独的绘图中)。在 x 轴(即时间)中,在每个时间旁边或下方,如果因子为真,我想写“是”,如果因子为假,则写“否”。

您可以使用以下行创建数据。

import pandas as pd
from datetime import datetime, timedelta
import matplotlib.pyplot as plt

# Function to create date range with 15-minute intervals
def create_date_range(start_date, end_date, interval):
    date_range = []
    current_date = start_date
    while current_date <= end_date:
        date_range.append(current_date)
        current_date += interval
    return date_range

# Function to create DataFrame
def create_dataframe(start_date, end_date, interval):
    date_range = create_date_range(start_date, end_date, interval)

    data = []
    for date_time in date_range:
        for camera in range(1, 5):
            for leg in range(1, 5):
                for movement in range(1, 4):
                    count = 1  # You can set count based on your requirements
                    control_factor = True if date_time.hour == 14 and camera == 1 else False
                    data.append([date_time, f'Cam{camera}', f'Leg{leg}', f'Move{movement}', count, control_factor])

    columns = ['DateTime', 'Camera', 'Leg', 'Movement', 'Count', 'control_factor']
    df = pd.DataFrame(data, columns=columns)
    return df

# Set start and end dates
start_date = datetime(2024, 1, 27, 14, 0, 0)
end_date = datetime(2024, 1, 27, 16, 0, 0)

# Set time interval
interval = timedelta(minutes=15)

# Create DataFrame
df = create_dataframe(start_date, end_date, interval)

# Display DataFrame
print(df)

我尝试了情节:

# List of unique cameras in your data
unique_cameras = df['Camera'].unique()

# Iterate over each camera
for camera in unique_cameras:
    # Filter data for the current camera
    df_camera = df[df['Camera'] == camera]

    # Group by DateTime, Leg, and Movement, summing the counts and taking the first control_factor value
    grouped_df = df_camera.groupby(['DateTime', 'Leg', 'Movement'])[['Count', 'control_factor']].agg({'Count': 'sum', 'control_factor': 'first'}).reset_index()

    # Plot the data
    plt.figure(figsize=(15, 8))
    ax = sns.barplot(x='DateTime', y='Count', hue='Leg', data=grouped_df, ci=None)

    # Rotate x-axis labels for better visibility
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')

    plt.title(f'Sum of Counts for Each Leg Over Time ({camera})')
    plt.xlabel('Time')
    plt.ylabel('Sum of Counts')

    # Annotate bars with control_factor values
    for index, row in grouped_df.iterrows():
        plt.text(index, row['Count'], str(row['control_factor']), ha='center', va='bottom')

    plt.show()

它在每个条形上显示 true 或 false,但我希望它位于 x 轴下方,并且我想让条形的颜色变浅,因此绘图颜色也很明显!与其他条形颜色相同,但颜色浅一点。

我也愿意使用其他图书馆。

python pandas plotly bar-chart axis-labels
1个回答
0
投票

由于这行代码,您会得到在 x 轴上延伸到无穷大的看起来很奇怪的图形,您在其中循环遍历每个行项,这是没有必要的:

    # # Annotate bars with control_factor values
for index, row in grouped_df.iterrows():
plt.text(index, row['Count'], str(row['control_factor']), ha='center', va='bottom')
  1. 要更改颜色,请参阅seaborn中的
    palette
    参数文档

我在下图中使用

palette = 'muted' 

  1. 要将 x 轴标签更改为控制因子,请更新您的
    set_xticklabels
    线。我为每个日期使用第一个控制因素,但如果您期望重复,您可能必须更改它
labs = grouped_df.groupby('DateTime').agg({'control_factor':'first'})['control_factor'].to_list()
ax.set_xticklabels(labs, rotation=45, ha='right')

结果图:

© www.soinside.com 2019 - 2024. All rights reserved.