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

使用Seaborn countplot处理Facebook帖子DataFrame多列二值数据:统一子图坐标轴及单图展示有效数据方案

Fixing Y-Axis Consistency and Creating a Single 'Yes' Count Plot

1. Aligning Y-Axes in Your 1x5 Countplots

Your current code creates subplots with independent y-axes, which is why their scales don’t match. There are two straightforward ways to fix this:

Option 1: Use Shared Y-Axis When Creating Subplots

Add sharey=True to your plt.subplots() call. This automatically syncs all y-axes to the same scale, making comparisons between subplots much easier:

import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(1, 5, sharey=True)
sns.countplot(data=df, x='Picture', ax=ax[0])
sns.countplot(data=df, x='Video', ax=ax[1])
sns.countplot(data=df, x='Youtube', ax=ax[2])
sns.countplot(data=df, x='Link', ax=ax[3])
sns.countplot(data=df, x='Teaser', ax=ax[4])

# Optional: Add titles to each subplot for clarity
ax[0].set_title('Picture')
ax[1].set_title('Video')
ax[2].set_title('Youtube')
ax[3].set_title('Link')
ax[4].set_title('Teaser')

plt.tight_layout()  # Prevents overlapping labels
plt.show()

Option 2: Manually Set Uniform Y-Limits

If you want more control over the y-axis range, calculate the maximum count across all your target columns and set that as the upper limit for every subplot:

import matplotlib.pyplot as plt
import seaborn as sns

target_cols = ['Picture', 'Video', 'Youtube', 'Link', 'Teaser']

# Find the highest count of either 0 or 1 across all columns
max_count = max(df[col].value_counts().max() for col in target_cols)

fig, ax = plt.subplots(1, 5)
for i, col in enumerate(target_cols):
    sns.countplot(data=df, x=col, ax=ax[i])
    ax[i].set_ylim(0, max_count)  # Apply same y-limit to all subplots
    ax[i].set_title(col)

plt.tight_layout()
plt.show()

2. Single Plot Showing Only 'Yes' (1) Entries

To visualize just the number of "Yes" entries for each column, you have two clean approaches:

Approach 1: Bar Plot of Summed 'Yes' Counts

Since each column uses 1 for "Yes", summing the column gives the total number of yes entries. We can create a summary DataFrame and plot it with sns.barplot:

import matplotlib.pyplot as plt
import seaborn as sns

target_cols = ['Picture', 'Video', 'Youtube', 'Link', 'Teaser']

# Create a DataFrame with column names and their yes counts
yes_counts = df[target_cols].sum().reset_index()
yes_counts.columns = ['Post_Type', 'Yes_Count']

# Plot the results
sns.barplot(data=yes_counts, x='Post_Type', y='Yes_Count', palette='viridis')
plt.title('Number of Posts with Each Content Type (Yes Only)')
plt.ylabel('Count of "Yes" Entries')
plt.xlabel('Content Type')
plt.show()

Approach 2: Count Plot with Filtered Data

If you specifically want to use sns.countplot, reshape your data to long format and filter for only the "Yes" values:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

target_cols = ['Picture', 'Video', 'Youtube', 'Link', 'Teaser']

# Reshape data from wide to long format
melted_df = df[target_cols].melt(var_name='Post_Type', value_name='Is_Present')

# Keep only rows where the value is 1 (Yes)
filtered_df = melted_df[melted_df['Is_Present'] == 1]

# Plot the count of yes entries per content type
sns.countplot(data=filtered_df, x='Post_Type', palette='viridis')
plt.title('Number of Posts with Each Content Type (Yes Only)')
plt.ylabel('Count of "Yes" Entries')
plt.xlabel('Content Type')
plt.show()

Both approaches will give you a clear, single plot showing how many times each content type was marked as "Yes".

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 21:39:11