יזואליזציה של נתונים היא כלי חשוב להצגת מידע בצורה גרפית וברורה.
בפייתון, ספריות כמו matplotlib
ו-seaborn
מאפשרות לנו ליצור גרפים, תרשימים, וטבלאות צבעוניות להצגת נתונים בצורה יעילה ואסתטית.
מה נלמד:
- שימוש ב-
matplotlib
: יצירת גרפים בסיסיים כמו קווי, עמודות, ועוגה. - שימוש ב-
seaborn
: יצירת גרפים מתקדמים יותר כמו heatmap ו-boxplot.
דוגמת קוד: שימוש ב-matplotlib
גרף עמודות להצגת תוצאות שחקנים במשחק הטריוויה.
import matplotlib.pyplot as plt
# Data: Player names and their scores
players = ["Alice", "Bob", "Charlie"]
scores = [7, 5, 8]
# Create a bar chart
plt.bar(players, scores, color="skyblue")
plt.title("Trivia Game Scores")
plt.xlabel("Players")
plt.ylabel("Scores")
plt.show()
הסבר על הקוד
- נתונים:
players
: רשימת שמות השחקנים.scores
: רשימת הציונים שלהם.
- יצירת גרף עמודות:
plt.bar
: יוצר גרף עמודות.plt.title
: מוסיף כותרת לגרף.plt.xlabel
ו-plt.ylabel
: מוסיפים כותרות לצירים.
- הצגת הגרף:
plt.show
: מציג את הגרף בחלון נפרד.
דוגמת קוד: שימוש ב-seaborn
גרף עוגה להצגת אחוז תשובות נכונות.
import matplotlib.pyplot as plt
# Data: Categories and percentages
categories = ["Correct", "Incorrect"]
percentages = [70, 30]
# Create a pie chart
plt.pie(percentages, labels=categories, autopct='%1.1f%%', colors=["green", "red"])
plt.title("Trivia Game Results")
plt.show()
הסבר על הקוד
- נתונים:
categories
: קטגוריות של תשובות נכונות ושגויות.percentages
: אחוזים לכל קטגוריה.
- יצירת גרף עוגה:
plt.pie
: יוצר גרף עוגה עם אחוזים.autopct
: מציג את האחוזים על גרף העוגה.
- הצגת הגרף:
plt.show
: מציג את הגרף.
תרגילים
תרגיל 1:
צרו גרף קווי (Line Graph) שמציג את הציון של כל שחקן לאחר כל משחק.
תרגיל 2:
צרו גרף עמודות שמשווה בין מספר השאלות הנכונות והשגויות בכל סבב משחק.
תרגיל 3:
השתמשו ב-seaborn
ליצירת גרף Boxplot שמציג את התפלגות הציונים של השחקנים.
תרגיל 4:
צרו גרף עוגה המציג את אחוזי השחקנים שעברו ציון מסוים (לדוגמה, 50%).
תרגיל 5:
אתגר: השתמשו בנתונים ממערכת הטריוויה שלכם ליצירת Heatmap המציג את ציוני השחקנים לפי שאלות.
הפרויקט הגדול: משחק הטריוויה
כעת נוסיף פונקציה במשחק שתציג ויזואליזציה של תוצאות השחקנים באמצעות matplotlib
.
עדכון קובץ quiz_game.py
import matplotlib.pyplot as plt
class QuizGame:
"""A class to manage the quiz game."""
def __init__(self, questions):
self.questions = questions # List of Question objects
self.scores = {} # Store player scores
def start(self, player_name):
"""Start the game for a player."""
score = 0
for question in self.questions:
print("\n" + question.text)
user_answer = input("Your answer: ").strip()
if question.is_correct(user_answer):
print("Correct!")
score += 1
else:
print(f"Wrong! The correct answer was: {question.answer}")
self.scores[player_name] = score
print(f"\n{player_name}, your final score is: {score}")
def visualize_scores(self):
"""Visualize scores of all players."""
players = list(self.scores.keys())
scores = list(self.scores.values())
plt.bar(players, scores, color="skyblue")
plt.title("Trivia Game Scores")
plt.xlabel("Players")
plt.ylabel("Scores")
plt.show()
עדכון קובץ main.py
def main():
"""Main function to run the quiz game."""
questions = load_questions()
quiz = QuizGame(questions)
while True:
print("\nOptions:")
print("1. Start Quiz")
print("2. View Scores")
print("3. Exit")
choice = input("Enter your choice: ").strip()
if choice == "1":
name = input("Enter your name: ").strip()
quiz.start(name)
elif choice == "2":
quiz.visualize_scores()
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")
שיפורים שנוספו לפרויקט:
- פונקציה
visualize_scores
:- יוצרת גרף עמודות שמציג את תוצאות כל השחקנים.
- תפריט ראשי:
- מאפשר לשחקנים להציג את הציונים שלהם בצורה גרפית.