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

获取YouTube频道TOP10最高播放量视频并绘制有序播放量柱状图的技术咨询

Got it, let's work through this problem step by step! You’re spot-on about the issues: your current code pulls the first 10 recent videos from the uploads playlist instead of the top 10 by view count, and the Y-axis isn’t ordered correctly because of how the data was being handled. Here’s how to fix both problems completely:

Step 1: Fix Data Fetching to Get Top 10 Videos by View Count

The core issue here is that you’re grabbing the first 10 videos from the uploads feed (newest ones) instead of sorting all videos by their view count first. We’ll adjust the code to collect all video metadata, match it with view counts, sort, and then pick the top 10.

Here’s the revised data fetching code:

from googleapiclient.discovery import build

# Replace with your actual API key
api_key = "YOUR_YOUTUBE_API_KEY"

youtube = build('youtube', 'v3', developerKey=api_key)

# Get channel basic stats (kept for consistency)
channel_request = youtube.channels().list(
    part='statistics', id='UC-lHJZR3Gqxt24_Td_AJ5Yw'
)
channel_response = channel_request.execute()
video_count = channel_response['items'][0]['statistics']['videoCount']

# Get uploads playlist ID
content_details = youtube.channels().list(
    id='UC-lHJZR3Gqxt24_Td_AJ5Yw', part='contentDetails'
).execute()
playlist_id = content_details['items'][0]['contentDetails']['relatedPlaylists']['uploads']

# Fetch all videos from the uploads playlist
videos = []
next_page_token = None
while True:
    playlist_request = youtube.playlistItems().list(
        playlistId=playlist_id, part='snippet', maxResults=50, pageToken=next_page_token
    ).execute()
    videos += playlist_request['items']
    next_page_token = playlist_request.get('nextPageToken')
    if not next_page_token:
        break

# Collect basic video info (ID + title) in a structured list
video_data = []
for video in videos:
    video_id = video['snippet']['resourceId']['videoId']
    title = video['snippet']['title']
    video_data.append({'id': video_id, 'title': title})

# Fetch view counts in batches (YouTube API allows max 50 IDs per request)
stats = []
for i in range(0, len(video_data), 40):
    batch_ids = ','.join([v['id'] for v in video_data[i:i+40]])
    stats_request = youtube.videos().list(id=batch_ids, part='statistics')
    stats += stats_request.execute()['items']

# Match view counts to their corresponding videos
for stat in stats:
    video_id = stat['id']
    # Convert view count to integer for proper sorting and plotting
    view_count = int(stat['statistics'].get('viewCount', 0))
    for video in video_data:
        if video['id'] == video_id:
            video['views'] = view_count
            break

# Sort videos by view count (descending) and filter out entries without view data
sorted_videos = sorted(
    [v for v in video_data if 'views' in v],
    key=lambda x: x['views'],
    reverse=True
)

# Grab the top 10 most viewed videos
top_10_videos = sorted_videos[:10]

# Prepare data for plotting
links = []
views = []
for video in top_10_videos:
    # Generate valid YouTube video links (your original links were incomplete)
    youtube_link = f"https://www.youtube.com/watch?v={video['id']}"
    link_html = f"<a href='{youtube_link}'>{video['title']}</a>"
    links.append(link_html)
    views.append(video['views'])

Step 2: Fix the Bar Chart for Proper Ordering

Now that we have the top 10 videos sorted by view count, the bar chart will naturally display them from highest to lowest. We’ll also ensure the Y-axis uses numerical values (since we converted view counts to integers) so the scale is accurate.

Here’s the revised plotting code:

from plotly.graph_objs import Bar
from plotly import offline

# Create bar chart data
data = [{
    'type': 'bar',
    'x': links,
    'y': views,
    'opacity': 0.6,
    'marker': {
        'color': 'rgb(150, 100, 20)',
        'line': {'width':1.5, 'color': 'rgb(25, 25, 25)'}
    },
}]

# Configure layout
my_layout = {
    'title': 'Top 10 Most Viewed Videos for the Channel',
    'titlefont': {'size':28},
    'xaxis': {
        'title': 'Videos',
        'titlefont': {'size': 24},
        'tickfont': {'size': 14},
        # Optional: Rotate labels to prevent overlap with long video titles
        'tickangle': -45
    },
    'yaxis': {
        'title': 'Views',
        'titlefont': {'size': 24},
        'tickfont': {'size': 14},
        # Ensure Y-axis uses linear numerical scaling
        'type': 'linear'
    },
}

# Generate and save the plot
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='youtube_top10_views.html')

Key Improvements Breakdown

  • Structured Data Matching: We use a list of dictionaries to pair each video’s ID, title, and view count, eliminating index mismatches between separate video and stats lists.
  • Proper Numerical Sorting: Converting viewCount from string to integer ensures we sort by actual view numbers (string sorting would fail for values like "100000" vs "99999").
  • Valid YouTube Links: Fixed the link format to point directly to each video on YouTube.
  • Y-Axis Order: Using integer view counts and setting yaxis.type to linear ensures Plotly renders the Y-axis in correct numerical order.
  • Readable X-Axis: Added optional label rotation to prevent long video titles from overlapping.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:54:08