Charts with matplotlib
Section 13: Pro drawing and chartsLesson 13.3 · ⏱ 12 min
Pros turn numbers into pictures. The matplotlib library works in Robo Python, and the chart appears in the result panel.
A line chart: the temperature during the week
import matplotlib.pyplot as plt
days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]
temps = [24, 26, 29, 31, 30, 27, 25]
plt.plot(days, temps, marker="o", color="tomato")
plt.title("Temperature this week")
plt.ylabel("°C")
plt.grid(True)
plt.show()
print("Highest:", max(temps), "on", days[temps.index(max(temps))])
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Highest: 31 on Tue

A bar chart: the class's results
The bars are green for those who got 85 or more. Notice the line that makes the list of colours in one line.
import matplotlib.pyplot as plt
names = ["Ali", "Mona", "Omar", "Sara"]
marks = [80, 93, 75, 88]
colors = ["green" if m >= 85 else "orange" for m in marks]
plt.bar(names, marks, color=colors)
plt.title("Class results")
plt.ylim(0, 100)
plt.show()
print("Average:", sum(marks) / len(marks))
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Average: 84.0

- Draw how many hours you slept on seven days.
- Draw the result of the dice project (11-2) as bars with plt.bar.
📌 Another example: the temperature line
A line chart: a week's temperature.
import matplotlib.pyplot as plt
days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"]
temps = [24, 26, 25, 29, 31, 30, 27]
plt.plot(days, temps, marker="o", color="orange")
plt.title("Temperature this week")
plt.ylabel("°C")
plt.show()
🐍 Open the code in Robo Python ↗
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
Bars: the number of students in each class.
👀 Show the solution🙈 Hide the solution
import matplotlib.pyplot as plt
classes = ["A", "B", "C", "D"]
students = [28, 32, 25, 30]
plt.bar(classes, students, color="teal")
plt.title("Students")
plt.show()
🐍 Open the code in Robo Python ↗
Result: four bars.
Medium
A pie: your favourite colours.
👀 Show the solution🙈 Hide the solution
import matplotlib.pyplot as plt
colors = ["red", "blue", "green"]
votes = [5, 9, 6]
plt.pie(votes, labels=colors, colors=colors)
plt.title("Favourite colour")
plt.show()
🐍 Open the code in Robo Python ↗
Result: a pie with three parts.
Hard
Bars for the results of 600 dice rolls.
👀 Show the solution🙈 Hide the solution
import matplotlib.pyplot as plt
import random
counts = [0] * 6
for i in range(600):
counts[random.randint(1, 6) - 1] += 1
plt.bar([1, 2, 3, 4, 5, 6], counts, color="purple")
plt.title("600 dice rolls")
plt.show()
🐍 Open the code in Robo Python ↗
Result: six bars close to each other.

