54.6k views
4 votes
. Create a text file that contains your expenses for last month in the following categories: • Rent • Gas • Food • Clothing • Car payment • Misc Write a Python program that reads the data from the file and uses matplotlib to plot a pie chart showing how you spend your money.

1 Answer

7 votes

Answer:

  1. from matplotlib import pyplot as plt
  2. with open("text.txt") as file:
  3. data = file.readlines()
  4. category = []
  5. amount = []
  6. for row in data:
  7. values = row.split(" ")
  8. category.append(values[0])
  9. amount.append(float(values[1]))
  10. figure = plt.figure()
  11. ax = figure.add_axes([0,0,1,1])
  12. ax.axis('equal')
  13. ax.pie(amount, labels = category, autopct='%1.2f%%')
  14. plt.show()

Step-by-step explanation:

Firstly, we need to import matplotlib library (Line 1).

Next, open a file stream and use readlines method to read the data from the text file (Line 4). Presume the data read from the text files are as follows:

Rent 450

Gas 150

Food 500

Clothing 120

Car 600

Create two lists, category and amount (Line 5-6). Use a for loop to traverse through the read data and use split method to break each row of data into two individual items. The first item is added to category list whereas the second item is added to amount list (Line 7 - 10).

Next, create a plot figure and then add the axes (Line 12 - 13). We can use the pie method to generate a pie chart (Line 15) by setting the amount list as first argument and category list as value of labels attributes. The output pie chart can be found in the attachment.

. Create a text file that contains your expenses for last month in the following categories-example-1
User Anarchivist
by
4.9k points