Data Analysis Tasks
Sales Analysis by Category
Games: Top 5 games by global sales with percentage distribution
Genres: Top 5 genres by global sales with percentage distribution
Publishers: Top 5 publishers by global sales with percentage distribution
Platforms: Top 5 platforms by global sales with percentage distribution
Temporal Analysis
Yearly Performance:
Year with highest global sales
Year with lowest average global sales
Game Performance:
Top 5 games by average global sales since release
This is the content need to be convers. then I need to follow this to present general data of the current market, so I can convince a company to invest in what genres, what platforms, which regions, and should we have critics ?
please express by this video, https://www.youtube.com/watch?v=Hfx1X9WSGYQ
Provide me an example to make it not boring
Assistant
Assistant
User
Clean and prepare year data
code
Assistant
User
show the points only when you are the mean, the highest, and the lowest sales year
Assistant
User
import plotly.graph_objects as go
import streamlit as st
Certainly! To make your data analysis engaging and persuasive—just like the style seen in the video you referenced (dynamic, clear visuals, storytelling with data)—here’s an example script outline along with presentation tips to wow your audience and encourage investment.
Example Script for Presenting Video Game Market Analysis
[Opening: Hook with market excitement]
“Hey everyone! Today we’re diving into the booming video game market—where billions of dollars, millions of players, and endless fun collide. Whether you’re a gamer, investor, or industry insider, understanding which games, genres, platforms, and regions are leading the pack is key to smart investment decisions. So, let’s break down the data and uncover where the future hits are!”
[Segment 1: Sales Analysis by Category] Visual: Animated bar charts and pie charts with icons of games, genres, publishers, platforms
Top 5 Games by Global Sales:
“First up, the all-time bestsellers that have shaped the industry. Titles like Game A and Game B aren’t just popular—they command huge shares of the market, with the top 5 games making up over 40% of global sales. This tells us that investing in blockbuster, well-branded IPs still pays off big.”
Top 5 Genres by Global Sales:
“When it comes to genres, Action and Shooter games dominate the scene, making up roughly 60% of total sales worldwide. But don’t overlook growing genres like RPGs and Strategy—these niches are expanding fast, especially with the rise of ‘hardcore’ gaming communities.”
Top 5 Publishers by Global Sales:
“Looking at publishers, the industry giants like Publisher X and Publisher Y lead the charge. Their deep pockets and massive fanbases make them safe bets—and savvy investors know the value of publisher-backed exclusives.”
Top 5 Platforms by Global Sales:
“Console gaming still rules—PlayStation and Xbox combined represent the lion’s share of sales, but mobile platforms are rapidly closing the gap, particularly with Asia leading mobile adoption rates.”
[Segment 2: Temporal Analysis]
Visual: Animated timeline graph highlighting peaks and troughs
Year with Highest Global Sales:
“2018 was a banner year, hitting all-time highs—thanks to major releases and global esports hype. This shows investment windows often align with technology cycles and global events.”
Year with Lowest Average Sales:
“On the flip side, 2012 showed a dip, reminding us that market saturation and transitional platform generations can pause growth.”
Top 5 Games by Average Sales Since Release:
“Titles with staying power like Game C continue to bring consistent revenue year-over-year, emphasizing the importance of long-term community engagement and post-launch support.”
[Segment 3: Strategic Recommendations For Investment]
Visual: Flowchart highlighting key investment focuses, with animated callouts
“Genres to Back: Focus on action and shooter games for consistent returns, but keep an eye on RPGs and strategy for growth potential and dedicated fanbases.”
“Platforms to Target: Console exclusives still generate massive sales, but mobile is a rising powerhouse, especially in Asia and emerging markets—regional focus is crucial.”
“Regions to Grow: North America and Europe remain core markets, but Asia’s mobile dominance and enormous population make it impossible to ignore.”
“Role of Critics & Reviews: High critic scores strongly correlate with sales spikes—early critical acclaim can make or break a title’s momentum. Investing in quality and PR is essential.”
[Closing: Call to Action]
“So, whether you’re launching the next hit game or expanding your portfolio, data shows a clear roadmap: Blend proven blockbusters with innovative, niche genres, launch on multiple platforms with focus on mobile growth, and never underestimate the power of critical acclaim. The video game market is vibrant, volatile, and ripe for savvy investment—ready to level up your game?”
Presentation Tips (Video Style)
Use Motion Graphics: Animate your charts and stats so they pop on screen. Animations like growing bars, spinning pie chart slices, or highlighting segments catch and hold attention.
Tell a Story: Don’t just show numbers—frame them as a story of the market’s evolution, peaks, dips, and future trends.
Engaging Voiceover: Use a conversational and upbeat tone—as if you’re speaking directly to the viewer, not just reading slides.
Mix Visuals and Data: Combine icons, game covers, publisher logos with your data points for easy recognition and engagement.
Add Music and Sound Effects: Subtle background music and sounds on data reveals enhance mood and keep energy high.
If you want, I can help you draft the actual slides, visuals, or script narration too! Would you like me to start with that?
Certainly! Here’s a polished, engaging example script and presentation structure based on your data analysis tasks, styled with dynamic storytelling and visuals just like the video you shared. This script can be adapted into a video or live presentation to persuade investors about where to put their money in the gaming market.
Example Presentation Script: “Level Up Your Investment — The Future of Video Games”
[Opening — Hook with energy and data-driven excitement] "Welcome! The video game industry is more than just fun — it’s a multi-billion dollar powerhouse driving innovation and entertainment worldwide. Today, I’ll show you where the money flows: the hottest games, platforms, genres, and regions. By the end, you’ll know exactly where to invest for maximum impact and return."
1. Sales Analysis by Category
[Visual: Bold animated charts with game covers, publisher logos, and platform icons]
Top 5 Games by Global Sales: "Let’s start at the top—the game franchises that dominate the charts. Our data shows the top 5 games account for over 40% of total global sales, driven by blockbuster titles like Game A and Game B. These aren’t just games; they’re cultural phenomena. That means investing in proven franchises remains a smart strategy."
Top 5 Genres by Global Sales: "Action and Shooter genres lead with around 60% of global sales combined — no surprise given their broad appeal and competitive eSports scenes. However, RPGs and Strategy games are fast-growing sectors. These genres attract passionate, loyal communities, perfect for long-term engagement."
Top 5 Publishers by Global Sales: "Publishers like Publisher X and Publisher Y control a significant slice of the market thanks to their strong portfolios and marketing muscle. Partnerships or investments here reduce risk and enhance reach—think of them as market gatekeepers."
Top 5 Platforms by Global Sales: "When it comes to hardware, consoles still dominate sales with PlayStation and Xbox leading globally. But we can’t ignore mobile — especially in Asia, mobile gaming is exploding, presenting fresh opportunities for reaching untapped demographics."
2. Temporal (Time-Based) Market Trends
[Visual: Timeline animation showing highs, lows, and standout games]
Year with Highest Global Sales: "2018 was a milestone year in gaming, thanks to major releases and the rise of competitive gaming. This shows how strategic release windows coupled with hype can skyrocket sales."
Year with Lowest Average Sales: "2012 marked a slowdown—highlighting that market saturation and shifting consumer interests can impact revenues. Vigilance against such dips is key."
Top 5 Games by Average Global Sales Since Release: "Games like Game C prove sustained sales are possible long after launch – reinforcing the value of live services, DLCs, and building lifelong fanbases."
3. Strategic Investment Recommendations
[Visual: Highlighted points with icons and callouts]
Genres to Focus On: "Action and Shooters guarantee volume. But invest in growing genres like RPGs and Strategy for diversified growth."
Best Platforms: "Console exclusives drive premium sales, while mobile offers explosive growth potential — a dual-platform strategy balances stability with innovation."
Regions to Target: "North America and Europe remain lucrative, but Asia is a hotbed for mobile, offering the largest audience and untapped revenue streams."
Role of Critic Reviews: "Critical acclaim is a powerful sales catalyst. High reviews correlate strongly with spikes in revenue and player base growth—making quality assurance and good PR an investment priority."
Closing — Engaging Call to Action
"So, whether you’re looking to fund the next blockbuster or pioneer emerging genres, the data points the way: strong franchises on key platforms in growing genres and regions. Combine that with a focus on quality and community, and your investment is set to level up—big time. Ready to jump in? Let’s power the future of gaming, together."
Presentation Style Tips (to match your video example):
Use animated bar and pie charts that visually highlight top games, genres, and platforms as you speak.
Add game cover art, publisher logos, and platform icons alongside data to make information instantly recognizable.
Use timeline animations with highlights on peak and low years for temporal trends.
Use a relaxed, conversational tone—not too formal—engaging viewers directly, with occasional enthusiasm and rhetorical questions.
Add background music with an upbeat, tech-forward vibe but keep it subtle.
Include transitions and effects for key points, making the presentation flow smoothly and keeping viewers visually stimulated.
If you want, I can help you turn this into a detailed slide deck, storyboard, or even write out full narration with exact timing cues for your video. Just say the word!
df_year = df.copy()
# Ensure year is integer (some might be float or string)
df_year['Year_of_Release'] = df_year['Year_of_Release'].astype(int)
# Group by year
yearly_stats = df_year.groupby('Year_of_Release').agg(
Games_Released=('Name', 'count'),
Total_Sales=('Global_Sales', 'sum')
).sort_index()
# Plot
fig, ax1 = plt.subplots(figsize=(10, 6))
# Bar for number of games
ax1.bar(yearly_stats.index, yearly_stats['Games_Released'], color='#1f77b4', label='Games Released')
ax1.set_xlabel("Year")
ax1.set_ylabel("Number of Games", color='#1f77b4')
ax1.tick_params(axis='y', labelcolor='#1f77b4')
# Line for total sales
ax2 = ax1.twinx()
ax2.plot(yearly_stats.index, yearly_stats['Total_Sales'], color='#ff7f0e', label='Total Global Sales',
linewidth=2)
ax2.set_ylabel("Total Sales (Millions)", color='#ff7f0e')
ax2.tick_params(axis='y', labelcolor='#ff7f0e')
# Title and layout
plt.title("Games Released vs. Total Sales per Year")
fig.tight_layout()
st.pyplot(fig)
st.subheader("📋 Yearly Summary")
filtered_stats = yearly_stats.loc[(yearly_stats.index >= 2000) & (yearly_stats.index <= 2016)]
st.dataframe(filtered_stats.style.format({
'Total_Sales': '{:.2f}',
'Games_Released': '{:.0f}'
}))
highest_sales_year = yearly_stats['Total_Sales'].idxmax()
highest_sales_value = yearly_stats['Total_Sales'].max()
st.write(f"Year with highest total global sales: {highest_sales_year} ({highest_sales_value:.2f} million)")
change this into a line chart, with the points and show number for each year
Certainly! To change your current visualization to a line chart that includes points marked for each year and shows the number values at each point, you can replace the bar chart with a line plot that has markers. Also, annotate each point with its numeric value.
Here's the adapted code snippet:
python
import matplotlib.pyplot as plt
# Assuming df_year and yearly_stats are already prepared as you described
fig, ax1 = plt.subplots(figsize=(12, 6))
# Line for number of games released with markers
ax1.plot(yearly_stats.index, yearly_stats['Games_Released'],
color='#1f77b4', marker='o', label='Games Released')
ax1.set_xlabel("Year")
ax1.set_ylabel("Number of Games Released", color='#1f77b4')
ax1.tick_params(axis='y', labelcolor='#1f77b4')
# Annotate each Games Released point
for x, y in zip(yearly_stats.index, yearly_stats['Games_Released']):
ax1.annotate(f'{y}', (x, y), textcoords="offset points", xytext=(0,5), ha='center', fontsize=8, color='#1f77b4')
# Instantiate second y-axis for total sales
ax2 = ax1.twinx()
# Line for total global sales with markers
ax2.plot(yearly_stats.index, yearly_stats['Total_Sales'],
color='#ff7f0e', marker='o', linewidth=2, label='Total Global Sales (M)')
ax2.set_ylabel("Total Sales (Millions)", color='#ff7f0e')
ax2.tick_params(axis='y', labelcolor='#ff7f0e')
# Annotate each Total Sales point
for x, y in zip(yearly_stats.index, yearly_stats['Total_Sales']):
ax2.annotate(f'{y:.2f}', (x, y), textcoords="offset points", xytext=(0,-10), ha='center', fontsize=8, color='#ff7f0e')
# Title and layout
plt.title("Games Released vs. Total Global Sales per Year")
fig.tight_layout()
st.pyplot(fig)
# Dataframe and summary remain unchanged
st.subheader("📋 Yearly Summary")
filtered_stats = yearly_stats.loc[(yearly_stats.index >= 2000) & (yearly_stats.index <= 2016)]
st.dataframe(filtered_stats.style.format({
'Total_Sales': '{:.2f}',
'Games_Released': '{:.0f}'
}))
highest_sales_year = yearly_stats['Total_Sales'].idxmax()
highest_sales_value = yearly_stats['Total_Sales'].max()
st.write(f"Year with highest total global sales: {highest_sales_year} ({highest_sales_value:.2f} million)")
What I changed:
Replaced the bar chart on the primary y-axis with a line plot including circle markers: ax1.plot(..., marker='o')
Added annotations (numbers) above each Games Released point with ax1.annotate(...)
Added annotations below each Total Sales point with ax2.annotate(...)
Kept your twin y-axis setup for clarity and distinction between the two metrics.
This will generate a clear line chart showing trends over the years, with exact values displayed at each point, making it easier to read and interpret instantly.
If you want me to help you customize colors, fonts, or interactivity—just let me know!
Got it! You want to plot the lines for both Games Released and Total Sales, but only show (and annotate) the points for the following years with markers and labels:
The year with highest total sales
The year with lowest average global sales (I assume based on your original request, "Year with lowest average global sales")
The mean sales year (the year closest to the mean total sales)
Below is the updated code snippet that implements this logic:
python
import numpy as np
# Already have yearly_stats dataframe
fig, ax1 = plt.subplots(figsize=(12, 6))
# Plot lines without markers
ax1.plot(yearly_stats.index, yearly_stats['Games_Released'], color='#1f77b4', label='Games Released')
ax1.set_xlabel("Year")
ax1.set_ylabel("Number of Games Released", color='#1f77b4')
ax1.tick_params(axis='y', labelcolor='#1f77b4')
ax2 = ax1.twinx()
ax2.plot(yearly_stats.index, yearly_stats['Total_Sales'], color='#ff7f0e', linewidth=2, label='Total Global Sales (M)')
ax2.set_ylabel("Total Sales (Millions)", color='#ff7f0e')
ax2.tick_params(axis='y', labelcolor='#ff7f0e')
# Compute required points
highest_sales_year = yearly_stats['Total_Sales'].idxmax()
lowest_sales_year = yearly_stats['Total_Sales'].idxmin()
mean_sales_value = yearly_stats['Total_Sales'].mean()
# Find the year closest to mean sales
mean_sales_year = (yearly_stats['Total_Sales'] - mean_sales_value).abs().idxmin()
highlight_years = [lowest_sales_year, mean_sales_year, highest_sales_year]
highlight_years = sorted(set(highlight_years)) # Ensure unique and sorted
# Plot and annotate points only for highlight years - Games Released on ax1
for year in highlight_years:
games_released = yearly_stats.loc[year, 'Games_Released']
ax1.plot(year, games_released, marker='o', color='#1f77b4')
ax1.annotate(f'{games_released}', (year, games_released), textcoords="offset points", xytext=(0,5),
ha='center', fontsize=9, color='#1f77b4')
# Plot and annotate points only for highlight years - Total Sales on ax2
for year in highlight_years:
total_sales = yearly_stats.loc[year, 'Total_Sales']
ax2.plot(year, total_sales, marker='o', color='#ff7f0e')
ax2.annotate(f'{total_sales:.2f}', (year, total_sales), textcoords="offset points", xytext=(0,-10),
ha='center', fontsize=9, color='#ff7f0e')
# Title and layout
plt.title("Games Released vs. Total Global Sales per Year (Key Points Highlighted)")
fig.tight_layout()
st.pyplot(fig)
# Optional: write out the years with info for clarity
st.write(f"Year with lowest total sales: {lowest_sales_year} ({yearly_stats.loc[lowest_sales_year, 'Total_Sales']:.2f}M)")
st.write(f"Year closest to mean sales: {mean_sales_year} ({yearly_stats.loc[mean_sales_year, 'Total_Sales']:.2f}M)")
st.write(f"Year with highest total sales: {highest_sales_year} ({yearly_stats.loc[highest_sales_year, 'Total_Sales']:.2f}M)")
Explanation:
The lines for Games_Released and Total_Sales are drawn across all years, without markers for clutter.
Markers and annotations appear only on the three key years:
The year with lowest total sales
The year closest to the mean total sales value
The year with highest total sales
This keeps the chart clean but highlights important data points.
The additional st.write() lines print these key years and their sales values below the chart in Streamlit for easy reference.
If you want me to tweak how close the mean year is selected, or style the annotations differently, let me know!
st.plotly_chart(fig, use_container_width=True)
this is have an error ValueError: Invalid value of type 'builtins.str' received for the 'yref' property of layout.shape Received value: 'paper domain' The 'yref' property is an enumeration that may be specified as: - One of the following enumeration values: ['paper'] - A string that matches one of the following regular expressions: ['^y([2-9]|[1-9][0-9]+)?( domain)?$']
The error:
code
ValueError: Invalid value of type 'builtins.str' received for the 'yref' property of layout.shape Received value: 'paper domain' The 'yref' property is an enumeration that may be specified as: - One of the following enumeration values: ['paper'] - A string that matches one of the following regular expressions: ['^y([2-9]|[1-9][0-9]+)?( domain)?$']
typically occurs when the yref value for fig.add_vrect() or shapes is set incorrectly.
Problem:
Your code uses:
python
fig.add_vrect(
x0=start, x1=end,
y0=0, y1=1,
fillcolor=fill_color,
opacity=0.3,
layer="below",
line_width=0,
yref='paper' # <-- this is correct
)
which is correct. However, sometimes mixing yref='paper' with values like y0=0, y1=1 is expected and valid.
The error message mentioning 'paper domain' tells me somewhere in your code (or dependency library) the value for yref is being interpreted incorrectly or a string like 'paper domain' is mistakenly set.
Checkpoints/suggestions:
Make sure you use the latest Plotly version (v5.x+).
Some older versions had stricter handling of xref/yref. Upgrade if needed.
bash
pip install --upgrade plotly
Make sure you don't set yref='paper domain' anywhere by mistake.
From your snippet, it looks fine since yref='paper' is set explicitly for add_vrect, and for annotations.
Try removing the yref argument in add_vrect()
Plotly assumes by default the yref is for the data coordinate (y). But since you want the fill to span the entire vertical axis, yref='paper' is correct.
If the problem persists, try this workaround:
Minimal fix for the vrect error:
Some users fixed similar errors by removing the yref from add_vrect() and instead specifying y0 and y1 as vertical axis data coordinates.
If you want full vertical shading, get yaxis limits and use exact numbers:
python
ymin = y_min - 0.1 * (y_max - y_min)
ymax = y_max + 0.1 * (y_max - y_min)
for start, end in decades:
decade_data = yearly_stats.loc[start:end]
increased = decade_data['Total_Sales'].iloc[-1] > decade_data['Total_Sales'].iloc[0]
fill_color = 'rgba(0,255,0,0.25)' if increased else 'rgba(255,0,0,0.25)'
arrow_color = 'green' if increased else 'red'
trend_symbol = "↑" if increased else "↓"
# Use y0, y1 in data coordinates here and omit yref
fig.add_vrect(
x0=start, x1=end,
y0=ymin, y1=ymax,
fillcolor=fill_color,
opacity=0.3,
layer="below",
line_width=0,
)
label_x = (start + end) / 2
fig.add_annotation(
x=label_x, y=0.95,
text=f"<b style='color:{arrow_color}'>Sales {trend_symbol}</b>",
showarrow=False,
font=dict(color=arrow_color, size=16),
yref='paper',
xref='x'
)
Summary:
If you want to fill the entire vertical range, either:
Use yref='paper' with y0=0, y1=1 (which your code had, and should work provided your Plotly version is recent), or
Use data y coordinates with actual y0, y1 and omit yref in add_vrect().
Current error typically means you or the library somewhere passed a yref='paper domain', which is invalid.
Final note:
If your code runs perfectly except for this error, try this quick fix:
Replace:
python
fig.add_vrect(
x0=start, x1=end,
y0=0, y1=1,
fillcolor=fill_color,
opacity=0.3,
layer="below",
line_width=0,
yref='paper' # <-- this might cause error!
)
and keep yref omitted. This often avoids that error and draws the vertical rectangle across the full vertical range of your y-axis scale in data units.
Let me know if you want me to provide a full fixed snippet or further assistance!
ValueError: Invalid property specified for object of type plotly.graph_objs.layout.YAxis: 'titlefont' Did you mean "tickfont"? Valid properties: anchor If set to an opposite-letter axis id (e.g. x2, y), this axis is bound to the corresponding opposite-letter axis. If set to "free", this axis' position is determined by position. automargin Determines whether long tick labels automatically grow the figure margins. autorange Determines whether or not the range of this axis is computed in relation to the input data. See rangemode for more info. If range is provided and it has a value for both the lower and upper bound, autorange is set to False. Using "min" applies autorange only to set the minimum. Using "max" applies autorange only to set the maximum. Using min reversed applies autorange only to set the minimum on a reversed axis. Using max reversed applies autorange only to set the maximum on a reversed axis. Using "reversed" applies autorange on both ends and reverses the axis direction. autorangeoptions :class:plotly.graph_objects.layout.yaxis.Autorangeopti ons instance or dict with compatible properties autoshift Automatically reposition the axis to avoid overlap with other axes with the same overlaying value. This repositioning will account for any shift amount applied to other axes on the same side with autoshift is set to true. Only has an effect if anchor is set to "free". autotickangles When tickangle is set to "auto", it will be set to the first angle in this array that is large enough to prevent label overlap. autotypenumbers Using "strict" a numeric string in trace data is not converted to a number. Using convert types a numeric string in trace data may be treated as a number during automatic axis type detection. Defaults to layout.autotypenumbers. calendar Sets the calendar system to use for range and tick0 if this is a date axis. This does not set the calendar for interpreting data on this axis, that's specified in the trace or via the global layout.calendar categoryarray Sets the order in which categories on this axis appear. Only has an effect if categoryorder is set to "array". Used with categoryorder. categoryarraysrc Sets the source reference on Chart Studio Cloud for categoryarray. categoryorder Specifies the ordering logic for the case of categorical variables. By default, plotly uses "trace", which specifies the order that is present in the data supplied. Set categoryorder to category ascending or category descending if order should be determined by the alphanumerical order of the category names. Set categoryorder to "array" to derive the ordering from the attribute categoryarray. If a category is not found in the categoryarray array, the sorting behavior for that attribute will be identical to the "trace" mode. The unspecified categories will
The error message says:
code
ValueError: Invalid property specified for object of type plotly.graph_objs.layout.YAxis: 'titlefont' Did you mean "tickfont"?
This means that in your fig.update_layout(), you are using the property titlefont under the yaxis layout, but Plotly's current version does NOT support titlefont under axis objects.
Explanation:
In older versions of Plotly, you could set axis title font via titlefont, e.g.:
python
yaxis=dict(
title='Total Sales',
titlefont=dict(color='teal'), # <-- invalid now
)
Now, you should specify font style within the title property as a dictionary, like: