matplotlib
matplotlib
Python Code
1 import matplotlib
2 matplotlib . use ( ’ TkAgg ’)
3 import matplotlib . pyplot as plt
4 import pandas as pd
5 # Exercise 1
6 data = {
7 ’ Month ’: [ ’ January ’ , ’ February ’ , ’ March ’ , ’ April ’ , ’ May ’
,
8 ’ June ’ , ’ July ’ , ’ August ’ , ’ September ’ ,
9 ’ October ’ , ’ November ’ , ’ December ’] ,
10 ’ Revenue ’: [5000 , 7000 , 8000 , 7500 , 8500 , 9000 , 9500 ,
8700 , 9200 , 9700 , 8800 , 10200] ,
11 ’ Expenses ’: [3000 , 4000 , 3500 , 3200 , 3800 , 4200 , 4000 ,
4500 , 4100 , 4300 , 3900 , 4600]
12 }
13 df = pd . DataFrame ( data )
14 # 1. Calculate the monthly profit : Profit = Revenue -
Expenses
15 print ( df )
16 monthly_profit = df [ ’ Revenue ’] - df [ ’ Expenses ’]
17 print ( monthly_profit )
18 # Add it as a new column to the DataFrame
19 df [ ’ MonthlyProfit ’] = monthly_profit
20 print ( df )
21
1
31 plt . plot ( df [ ’ Month ’] , df [ ’ Revenue ’] , label = ’ Revenue ’ , marker
= ’o ’)
32 plt . plot ( df [ ’ Month ’] , df [ ’ Expenses ’] , label = ’ Expenses ’ ,
marker = ’o ’)
33 plt . plot ( df [ ’ Month ’] , df [ ’ MonthlyProfit ’] , label = ’ Monthly
Profit ’ , marker = ’o ’)
34 # Customization
35 plt . title ( ’ Revenue , Expenses , and Profit Over the Months ’)
36 plt . xlabel ( ’ Month ’)
37 plt . ylabel ( ’ Amount ’)
38 plt . xticks ( rotation =45) # To rotate the labels
39 plt . grid ( True )
40 plt . legend ( title = " Metrics " )
41 plt . show ()
42
51 # Exercise 2
52 import pandas as pd
53 # Read the CSV file into a DataFrame
54 df = pd . read_csv ( ’ Sales . csv ’)
55 # Convert the ’ Date ’ column to datetime format
56 df [ ’ Date ’] = pd . to_datetime ( df [ ’ Date ’ ])
57 # Display the DataFrame
58 print ( df )
59
2
76 plt . xlabel ( ’ Region ’)
77 plt . ylabel ( ’ Total Sales ’)
78 plt . grid ( axis = ’y ’ , linestyle = ’ -- ’ , alpha =0.6)
79 plt . show ()
80
103 # The category with the highest quantity will be the first
one
104 explode = [0.2 , 0 , 0]
105
3
114 ’ fontsize ’: 14 , # Font size
115 ’ fontweight ’: ’ bold ’ , # Font weight
116 ’ color ’: ’ purple ’ , # Font color
117 }
118 plt . title ( ’ Total Quantity Sold by Category ’ , fontdict =
s ub pl o t_ t it le _ fo n t_ di c t )
119