-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject.Rmd
2144 lines (1586 loc) · 108 KB
/
project.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Analyzing a Superstore dataset"
author: "Laia Porcar, Luis Marcos López, Philippe Robert"
date: "7/9/2022"
output:
html_document:
toc: yes
df_print: kable
pdf_document:
toc: yes
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(warn=-1)
```
The aim of this work is to analyze a dataset of purchases in an anonymous online store. The analysis will consist of data cleaning, exploratory data analysis (EDA), a simple case of linear regression, a more complete study of multiple linear regression and finally a binary classification problem.
## Installs and libraries
```{r, results="hide", message = FALSE}
# Installs
#install.packages("caret")
#install.packages("car")
#install.packages("ggplot2")
#install.packages("devtools")
#install.packages("ggcorrplot")
#devtools::install_github("laresbernardo/lares")
#devtools::install_github("ProcessMiner/nlcor")
#install.packages("ISLR2")
#devtools::install_github("kassambara/ggpubr")
#install.packages("zoo")
#install.packages("ROSE")
#install.packages("e1071")
#install.packages("klaR")
#install.packages("treemapify")
#install.packages("glmnet")
# Libraries
library(knitr)
library(tidyverse)
library(ggplot2)
library(forcats)
library(dplyr)
library(ggcorrplot)
library(lares)
library(treemapify)
library(MASS)
library(devtools)
library(ISLR2)
library(ggpubr)
library(zoo)
library(reshape2)
library(ROSE) # for undersampling/oversampling
library(e1071) # for naive Bayes
library(caret)
library(klaR)
library(car) # for calculation of VIF in multiple linear regression
library(glmnet)
library(choroplethr)
library(choroplethrMaps)
library(kableExtra)
library(magrittr)
```
## Importing Dataset
The dataset has been obtained from Kaggle, the famous data science platform. It is publicly available for educational purposes and has been downloaded as csv file for ease of use. It consists of 9994 purchases made from an anonymous online store and contains the following features:
Row ID => Unique ID for each row.<br>
Order ID => Unique Order ID for the purchase.<br>
Order Date => Order Date of the product.<br>
Ship Date => Shipping Date of the product.<br>
Ship Mode=> Shipping Mode specified by the customer.<br>
Customer ID => Unique ID to identify the customer.<br>
Customer Name => Name of the customer.<br>
Segment => The segment to which the customer belongs.<br>
Country => Country where the purchase was made.<br>
City => City where the purchase was made.<br>
State => State where the purchase was made.<br>
Postal Code => Postal Code of the customer.<br>
Region => Region where the customer belongs.<br>
Product ID => Unique ID of the product.<br>
Category => Category of the product ordered.<br>
Sub-Category => Sub-Category of the product ordered.<br>
Product Name => Name of the product.<br>
Sales => Sales of the product.<br>
Quantity => Quantity of the product.<br>
Discount => Discount provided.<br>
Profit => Profit/Loss incurred.<br>
```{r results = 'asis'}
# Read the dataset
df <- read.csv("~/Luis/Universidad/Master_DS/Second_semester/Statistical_Learning/Project/Sample-Superstore.csv",header=TRUE)
#kable(df[1:5,])
df[1:15,] %>%
kable(format = "html", col.names = colnames(df)) %>%
column_spec(c(2:21), width_min = "0.8in") %>%
kable_styling() %>%
kableExtra::scroll_box(width = "100%", height = "300px")
```
## Data cleaning
In this section we will carry out the cleaning of the data. First of all we will check basic information, such as missing values (in the form of NaN, NA and Null), duplicates, number of unique values and determine which columns can be removed and which can be modified or created. After, we will focus our efforts on determining outliers.
### Basic data cleaning
With a summary of the data we can know important information about each feature, such as its class, its mean, quartiles, maximum and minimum.
```{r}
summary(df)
```
Check if there are Na and NAN:
```{r}
is.null(df)
sum(is.na(df))
sum(is.nan(as.matrix(df)))
```
There are no missing values of any type. This is certainly not very surprising since most datasets available in Kaggle for educational use have usually gone through some sort of cleaning beforehand. Therefore, this means that for now we still have the 9994 examples available.
Number of duplicates:
```{r}
sum(duplicated(df))
```
No duplicates present. Same reasoning as for missing values apply.
Let's have a look at the unique values in each column.
```{r}
cat(paste("Sub.Category: ", length(unique(df[["Sub.Category"]])) ), sep="\n")
cat(paste("Category: ", length(unique(df[["Category"]]))), sep="\n")
cat(paste("Country: ", length(unique(df[["Country"]]))), sep="\n")
cat(paste("Region: ", length(unique(df[["Region"]]))), sep="\n")
cat(paste("State: ", length(unique(df[["State"]]))), sep="\n")
cat(paste("City: ", length(unique(df[["City"]]))), sep="\n")
cat(paste("Ship.Mode: ", length(unique(df[["Ship.Mode"]]))), sep="\n")
cat(paste("Customer.ID: ", length(unique(df[["Customer.ID"]]))), sep="\n")
cat(paste("Order.ID: ", length(unique(df[["Order.ID"]]))), sep="\n")
```
It's shown that there are 17 different sub-categories grouped in 3 categories, 532 cities belonging to 49 states and 4 regions, 4 ship modes and 793 different customers. Having 9994 orders and 793 customers means a good quantity of those customers (if not all) have purchased more than one subcategory or made more than one order. Different subcategory products bought together will be found in different rows of the dataset, even though they share the same order number. This conclusion can be drawn from the number of unique orders, which is slightly bigger than half of the number of purchases and the fact that there are no duplicates . This is all good information that we can use later in the Exploratory Data Analysis section.
We can get rid of some columns. The name of the customer is not very useful when we already have a unique customer ID for each client. This is also a good practice to maintain the anonymity of customers. The Country column is also not relevant since there is only data for the USA. And finally the postal code column won't be needed since we will not carry our analysis in such detail and with the city and state columns it will be enough.
```{r}
df = df[-c(1,7,9,12)]
```
Convert date columns to date format:
```{r}
df$Order.Date <- as.Date(df$Order.Date, format = "%m/%d/%Y")
df$Ship.Date <- as.Date(df$Ship.Date, format = "%m/%d/%Y")
```
Next, we can create some useful columns. For example, if we subtract the *Order.Date* from the *Ship.Date* we get the *Processing.Time*, this is, how much time the store needed to ship the product since it was ordered. The gross margin is also useful to have, it is calculated as the ratio of *Profit* to *Sales* multiplied by 100 (in %). Finally, we can separate the *Order.Date* column into three other columns for the year, the month and the information concerning the year and month.
```{r}
df$Order.Year <- format(df$Order.Date,"%Y")
df$Order.Year <- as.numeric(df$Order.Year)
df$Order.Month <- format(df$Order.Date,"%m")
df$Order.Month <- as.numeric(df$Order.Month)
df$Order.Year_month <- format(df$Order.Date,"%Y-%m")
df$Order.Year_month <- as.Date(paste(df$Order.Year_month,"-15",sep=""))
df$Order.Date <- as.numeric(df$Order.Date)
df$Processing.Time <- df$Ship.Date - df$Order.Date
df$Processing.Time <- as.numeric(df$Processing.Time)
df$Gross.Margin <- (df$Profit/df$Sales)*100
```
Let's have a look at the final structure of the data after doing the aforementioned modifications.
```{r}
summary(df)
```
### Outliers detection
Let's have a look again at the summary of columns that could potentially have some outliers.
```{r}
summary(df$Sales)
summary(df$Quantity)
summary(df$Discount)
summary(df$Profit)
summary(df$Processing.Time)
summary(df$Order.Year)
summary(df$Gross.Margin)
summary(df$Order.Date)
```
By checking the maximum and minimum values it is hard to tell if there could be outliers, since, even though in some cases the maxima are a bit far from the 3rd quartile, they are all possible values for the quantities they describe.
Let's plot the numerical variables to have a look at their distribution.
```{r warning = FALSE, message = FALSE, fig.height=32, fig.width=32, dev = "png", dpi = 300}
hst_Sales <- ggplot(df) + aes(x = Sales) +
geom_histogram(color="white", fill="#80b1d3", bins = 100) +
labs(title="", x="Sales", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
hst_Quantity <- ggplot(df) + aes(x = Quantity) +
geom_histogram(color="white", fill="#80b1d3", bins = 14) +
labs(title="", x="Quantity", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
title = element_text(size = 16))
hst_Discount <- ggplot(df) + aes(x = Discount) +
geom_histogram(color="white", fill="#80b1d3", bins = 9) +
labs(title="", x="Discount", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
title = element_text(size = 16))
hst_Profit <- ggplot(df) + aes(x = Profit) +
geom_histogram(color="white", fill="#80b1d3", bins = 120) +
labs(title="", x="Profit", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
title = element_text(size = 16))
hst_Processing <- ggplot(df) + aes(x = Processing.Time) +
geom_histogram(color="white", fill="#80b1d3", bins = 8) +
labs(title="", x="Processing time", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
title = element_text(size = 16))
hst_Year <- ggplot(df) + aes(x = Order.Year) +
geom_histogram(color="white", fill="#80b1d3", bins = 4) +
labs(title="", x="Years", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
title = element_text(size = 16))
################################################################################
require(gridExtra)
grid.arrange(hst_Sales, hst_Quantity, hst_Year, hst_Discount, hst_Processing, hst_Profit, ncol = 2, nrow = 3)
```
Processing time, Years, Discount and Quantity look fine. The latter presents some right skewness but for our criteria is not a case of possible outliers. The Sales and profit plots require some transformation before being able to draw a conclusion. A log transformation should do the work.
```{r message = FALSE, fig.height=26, fig.width=32, dev = "png", dpi = 300}
df_positive_profit <- df %>% filter(Profit >= 0)
df_negative_profit <- df %>% filter(Profit < 0)
plot1 <- ggplot(df_positive_profit) + aes(x = log(Profit)) +
geom_histogram(color="white", fill="#80b1d3", bins = 12) +
labs(title="", x="Log(Pos. Profit)", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot2 <- ggplot(df_negative_profit) + aes(x = log(-Profit)) +
geom_histogram(color="white", fill="#80b1d3", bins = 12) +
labs(title="", x="Log(Neg. Profit)", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot3 <- ggplot(df) + aes(x = log(Sales)) +
geom_histogram(color="white", fill="#80b1d3", bins = 30) +
labs(title="", x="log(Sales)", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28), title = element_text(size = 16))
df_profit <- df[!(df$Profit < 600 & df$Profit >= -600 ),]
plot4 <- ggplot(df_profit) + aes(x = Profit) +
geom_histogram(color="white", fill="#80b1d3") +
labs(title="", x="Profit (omitting central values)", y="Frequency") +
theme_minimal()+
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28), title = element_text(size = 16))
################################################################################
require(gridExtra)
grid.arrange(plot1, plot2, plot3, plot4, ncol = 2, nrow = 2)
```
The log of *Sales* looks pretty Gaussian to the eye and the skewness is gone. The variable *Profit* presents both negative and positive values, therefore we separate them both in two histograms, taking the absolute value of the negative one. We also show the *Profit* distribution without any transformation but hiding the central highest values so the the tails are easier to see. There seem to be no strong indications of the presence of outliers for any of the quantities.
Finally, we can check the box plots of all numeric variables. Box plots are one of the most useful tools in outliers identification.
```{r message = FALSE, fig.height=26, fig.width=32, dev = "png", dpi = 300}
plot1 <- ggplot(df, aes(y = Quantity)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot2 <- ggplot(df, aes(y = Discount)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot3 <- ggplot(df, aes(y = Sales)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot4 <- ggplot(df, aes(y = Profit)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot5 <- ggplot(df, aes(y = Processing.Time)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
# Alternatively we can also separate the quantitative variable per the qualitative one, for example:
plot6 <- ggplot(df, aes(x = Category, y = Discount)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot7 <- ggplot(df, aes(x = Region, y = Sales)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
plot8 <- ggplot(df, aes(x = Category, y = Profit)) +
geom_boxplot(color="black", fill="#80b1d3") + theme_minimal() +
theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28), title = element_text(size = 16))
################################################################################
require(gridExtra)
grid.arrange(plot1, plot2, plot3, plot4, plot5, plot6, plot7, plot8, ncol = 4, nrow = 2)
```
Except for *Processing Time*, there are potential outliers in almost all variables. *Sales* and *Profits* stand out. *Quantity* and *Discount* present a few possible outliers. As seen at the beginning, the maximum discount corresponds to 0.8, which although rare, it is a value that can occur on specific occasions. The maximum value of *Quantity* is 14, which is also perfectly possible, especially in the case of items that are purchased in large quantities and also given that we have several types of customers. Those buying for their business or company would be expected to buy in larger quantities.
For these reasons and those stated above, we believe that we do not have enough information about the store and its functioning to be able to really determine if some of the purchases made can be classified as outliers. In the absence of a safe and definitive criterion, we chose not to eliminate any of the potential outlier points.
## Relevant questions
As a starting point to develop the following sections of the work, we will try to answer the following questions.
* Which subcategories are more popular? Are those the ones that generate more profit?
* Do different segments prefer different ship modes?
* In which states are there more orders? And in which cities? Do they correspond to the ones that generate more profit?
* Which is the top-10 clients according to purchases and to which segment do they belong? Are they the ones that generate more profit?
* Is there a difference between the profit generated by each segment in the different categories? And between the profit generated in each region in each category?
* Does the quantity of products bought change in each category when there is a discount?
* How does the profit change for different discount ranges? What would be a threshold discount for positive/negative profits?
* How do orders behave throughout the year? Can we identify some patterns?
* Do sales and profits behave similarly for every month?
* Which segment is generating more sales? In which region?
* Do we observe a different behavior for holiday periods (November and December in the USA)?
* What is the relation between profit and sales? Is it linear?
* How accurately can we estimate this relation?
* How accurately can we predict future profits based on sales?
* What features are more relevant when determining the profit?
* Is there any interaction among the different features?
* Is it possible to predict if a purchase will result on positive or negative profit? Which features are more relevant for this task? How accurate is the prediction?
## Exploratory Data Analysis
```{r}
summary(df)
```
### Analysis of discrete variables
First of all let's see the proportion that each subcategory represents in general and inside each category. We can see that *Binders*, *Paper*, *Furnishing* and *Phones* (in that order) are the more popular subcategories. The less popular ones are *Copiers* and *Machines*, followed by *Bookcases*, *Envelopes*, *Fasteners* and *Supplies*. When talking about categories, *Office Supplies* is the most represented one. Both *Technology* and *Furniture* have a similar number of items.
```{r, message = FALSE, fig.height=22, fig.width=32, dev = "png", dpi = 300}
plotdata <- df %>% count(Sub.Category) %>% arrange(desc(Sub.Category)) %>%
mutate(prop = round(n*100/sum(n), 1), lab.ypos = cumsum(prop) - 0.5*prop)
plotdata$label <- paste0(plotdata$Sub.Category, "\n", round(plotdata$prop), "%")
plot1 <- ggplot(plotdata, aes(x = "", y = prop, fill = Sub.Category)) +
geom_bar(width = 1, stat = "identity", color = "white") +
coord_polar(theta = "y", start = 1.4, direction = -1) +
theme(legend.position = "FALSE", axis.text=element_text(size=32))+
scale_y_continuous(breaks=cumsum(plotdata$prop) - plotdata$prop / 2,
labels= plotdata$label) + labs(y = "", x = "", title = "") + theme_minimal()+ theme(axis.text=element_text(size=24), axis.title.x = element_text(size =28), axis.title.y = element_text(size = 28), legend.text = element_text(size =24),
legend.title = element_text(size =28))
################################################################################
df_cat <- df %>% group_by(Category, Sub.Category) %>% summarize(count=n())
plot2 <- ggplot(df_cat, aes(area=count, label=Sub.Category, fill=Category, subgroup=Category))+
geom_treemap()+
geom_treemap_subgroup_border(colour = "white", size = 5)+
geom_treemap_subgroup_text(color='white', alpha=0.3, size=48,
place='center', fontface='bold')+
geom_treemap_text(color='white', place='center', size=34) +
theme(legend.text = element_text(size = 24),
legend.title = element_text(size = 28))
################################################################################
require(gridExtra)
grid.arrange(plot1, plot2, ncol = 2, nrow = 1)
```
Now we will construct a set of useful barplots to understand better some relations between the features in the dataset. First, we plot the top-15 states and cities where more orders are made. California, New York and Texas are the states that make the most orders. Most of these states belong to the top-15 most populated states in the USA for the years of interest. Regarding the top-15 cities, they are mostly, as expected, cities of the states where more orders have been made. Los Angeles and New York City are the top-2 since they are also the most populated cities in the USA. The most bought category for all states and cities is *Office Supplies*.
The most popular shipping mode is *Standard Class* for all segments, followed by *Second Class* and *First Class*. This is also true for each category. The amount of orders belonging to the *Office Supplies* category is more than the sum of the orders of the two other categories.
The south region presents the lowest amount of orders while the west region the most. *Consumer* is the type of client that more orders make for each region and *Home Office* the one that makes less.
Regarding the profit, East and West are the regions that more profit generate. *Consumer* type of clients represent the most profit but also the most losses.
```{r, message = FALSE, fig.height=36, fig.width=32, dev = "png", dpi = 300}
top_states <- tail(names(sort(table(df$State))),15)
df_top_states <- df %>% filter(df$State %in% top_states)
plot1 <- ggplot(df_top_states, aes(x = State, fill = Category)) +
geom_bar(position = "stack", bins = 15) +
labs(title="", x="State", y="Orders") +
theme_minimal()+
theme(axis.text=element_text(size=24), axis.text.x = element_text(angle=45),
axis.title.x = element_text(size =28), axis.title.y=element_text(size=28),
plot.title = element_text(size = 24, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size =28)) +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
top_cities <- tail(names(sort(table(df$City))),15)
df_top_cities <- df %>% filter(df$City %in% top_cities)
plot2 <- ggplot(df_top_cities, aes(x = City, fill = Category)) +
geom_bar(position = "stack", bins = 15) +
labs(title="", x = "City", y="Orders") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.text.x = element_text(angle=45),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size=28),
plot.title = element_text(size = 24, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28))+
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
df2 <- df %>% group_by(Category)
plot3 <- ggplot(data = df2,aes(Category, fill=`Ship.Mode`))+
geom_bar(position = 'stack')+
labs(title='', x='Category', y='Orders') +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 24, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size =28)) +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
df2 <- df %>% group_by(Segment)
plot4 <- ggplot(data = df2, aes(Segment, fill=`Ship.Mode`))+
geom_bar(position = 'stack')+
labs(title='', x='Segment', y='Orders') +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 24, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28))+
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
df2 <-df %>% group_by(Region)
plot5 <- ggplot(data = df2, aes(Region, fill=`Segment`))+
geom_bar(position = 'stack')+
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 24, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28))+
labs(title='', x='Region', y='Orders') +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
plot6 <- ggplot(df, aes(x=Region, y=Profit, fill = Segment)) +
geom_bar(stat = "identity") + labs(x="Region", y="Profit") + theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 16, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))+
scale_y_continuous(label = scales::dollar)+
geom_hline(yintercept=0, linetype="dashed")
################################################################################
require(gridExtra)
grid.arrange(plot1, plot2, plot3, plot4, plot5, plot6, ncol = 2, nrow = 3)
```
In the next plots we represent the total number of orders, sales and profit generated in each month. During the last months of the year both sales and orders are higher than at the beginning. Up to three times more orders and sales are made in November and December as compared to January and February. Also, both positive and negative profits increase towards the last months of the year. The number of orders also increase throughout the years and the proportions of the shipping mode used remain the same.
```{r, message = FALSE, fig.height=28, fig.width=32, dev = "png", dpi = 300}
# Purchases, sales and benefits for years and months. In what months do people usually buy more?
# Are the sales generally increasing over time? Are there more sales on Christmas, Black Friday...?
plot1 <- ggplot(df, aes(x=Order.Month, fill = Category))+
geom_bar(position = "stack", bins = 12)+
labs(title="", x = "Month", y="Orders")+
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 24, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28))+
scale_x_discrete(limits= seq(1,12))+
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
plot2 <- ggplot(df, aes(x=Order.Month, y=Sales, fill = Category))+
geom_bar(stat = "identity", bins = 12) + labs(title="", x="Month", y="Sales") +
theme_minimal() + theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
plot.title = element_text(size = 16, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_x_discrete(limits= seq(1,12)) + scale_y_continuous(label = scales::dollar) +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
plot3 <- ggplot(df, aes(x=Order.Month, y= Profit, fill = Category))+
geom_bar(stat = "identity") + labs(title="", x="Month", y="Profit") +
theme_minimal() + theme(axis.text=element_text(size=24),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
plot.title = element_text(size = 16, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_x_discrete(limits= seq(1,12)) + scale_y_continuous(label = scales::dollar) +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))+
geom_hline(yintercept=0, linetype="dashed")
################################################################################
# Is there any preference on shipment methods over the years?
plot4 <- ggplot(df, aes(x=Order.Year, fill = Ship.Mode))+
geom_bar(position = "stack", bins = 4)+
labs(title="", x = "Year", y="Orders")+
theme_minimal()+
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 24, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
require(gridExtra)
grid.arrange(plot2, plot1, plot3, plot4, ncol = 2, nrow = 2)
```
Next off, we study which subcategories represent the highest profits (sum of positive and negative) and which the highest losses (sum of positive and negative). Copiers belong to the top-5 subcategories that generate positive profit, but it is one of the least popular subcategories as we saw at the beginning of this section. Tables and Machines are subcategories that need to be closely watched given their losses are very high.
```{r, message = FALSE, fig.height=22, fig.width=32, dev = "png", dpi = 300}
df_subcat <- df %>% group_by(Sub.Category) %>% summarise(prof = sum(Profit))
df_subcat <- df_subcat[order(df_subcat$prof),]
top_subcat_neg <- head(df_subcat$Sub.Category, 5)
top_subcat_pos <- tail(df_subcat$Sub.Category, 5)
df_top_pos <- df %>% filter(Sub.Category %in% top_subcat_pos)
plot_top_pos <- ggplot(df_top_pos, aes(x = Sub.Category, y = Profit, fill = Segment)) +
geom_bar(stat="identity", position = "stack", bins = 5) +
labs(x = "Subcategory", y= "Profit") +
theme_minimal() + scale_y_continuous(label = scales::dollar) +
theme(axis.text=element_text(size=24), axis.text.x = element_text(angle=45),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
ggtitle("Top subcategories with positive profit") +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))+
geom_hline(yintercept=0, linetype="dashed")
################################################################################
df_top_neg <- df %>% filter(Sub.Category %in% top_subcat_neg)
plot_top_neg <- ggplot(df_top_neg, aes(x = Sub.Category, y = Profit, fill = Segment)) +
geom_bar(stat = "identity", position = "stack", bins = 5) +
labs(x = "Subcategory", y= "Profit") + scale_y_continuous(label = scales::dollar) +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.text.x = element_text(angle=45),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
ggtitle("Top subcategories with negative profit") +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))+
geom_hline(yintercept=0, linetype="dashed")
################################################################################
require(gridExtra)
grid.arrange(plot_top_pos, plot_top_neg, ncol = 2, nrow = 1)
```
#### Total orders by state
In the map presented below we can see which of the states are associated with a highest number of orders. This information completes the one given earlier about the top-10 states regarding the number of orders. As expected, the most populated states are those where more orders are made: California, Texas, Florida, New York, Pennsylvania... Likewise, the most sparse are associated with a smaller number of purchases.
```{r, message = FALSE, fig.height=8, fig.width=8, fig.align="center"}
df_mapusa <- df %>% group_by(State)
df_mapusa <- df_mapusa %>% summarize(orders = n())
df_mapusa$region <- tolower(df_mapusa$State)
df_mapusa$value <- df_mapusa$orders
continental_us_states <- names(table(df_mapusa$region))
state_choropleth(df_mapusa, num_colors=9, zoom = continental_us_states) +
scale_fill_brewer(palette="YlOrBr") +
labs(fill = "Total orders")
```
#### Total profit by state
We can now check which states generate the most and the least profit and study if they are related to the ones where more purchases were made. Indeed, some states as California and New York and Washington generate both big profit and number of orders. Nevertheless, states as Florida, Texas, Pennsylvania and Colorado despite being associated with high number of purchases generate very low or negative profit. Also remarkable is that states like Nevada and Montana generate a decent amount of profits although they are states where not many purchases are made.
```{r, message = FALSE, fig.height=8, fig.width=8, fig.align="center"}
df_mapusa <- df %>% group_by(State) %>% summarize(profitss = sum(Profit))
df_mapusa$region <- tolower(df_mapusa$State)
df_mapusa$value <- df_mapusa$profitss
continental_us_states <- names(table(df_mapusa$region))
state_choropleth(df_mapusa, num_colors=9, zoom = continental_us_states) +
scale_fill_brewer(palette="YlOrBr") +
labs(fill = "Total profit")
```
#### Analysis of holiday and preholiday periods
Next we see how the store has done in the four years our data covers, by studying how sales and profits have behaved (left barplot below). During the first two years the number of sales remained constant, while the profit increased slightly, proving the store was able to improve their gross margin. Next two years both sales and profits grew to a greater extent.
We are also interested in analyzing what impact the holiday season in the USA (last two months of the year) has on the number of orders (right barplot below). First, there is an increase in the number of orders throughout the years for both periods. Furthermore, the number of orders during holiday season is almost half of the number for the rest of the year; maintaining this constant relationship over the years. Notice that we are comparing two months against 10. Therefore holiday season has a big impact on the number of orders that are made in the store.
```{r, message = FALSE, fig.height=18, fig.width=32, dev = "png", dpi = 300}
Sales_per_year <- df %>% group_by(Order.Year) %>% summarise(s = sum(Sales))
Profit_per_year <- df %>% group_by(Order.Year) %>% summarise(p = sum(Profit))
Sales <- Sales_per_year$s
Profit <- Profit_per_year$p
Years <- c("2014", "2015", "2016", "2017")
df_growthsales_profit <- data.frame(Sales, Profit, Years)
df_growthsales_profit2 <- melt(df_growthsales_profit, id.vars="Years")
plot_year <- ggplot(df_growthsales_profit2, aes(x=Years, y=value, fill=variable))+
geom_bar(stat="identity", position="dodge") +
labs(title="Sales and Profit per year", x = "Years", y="USD") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_fill_manual(values = c("#da6474", "#80b1d3", "#fdb462", "#7fc97f"))
###############################################################################
Order_preholiday <- df %>% filter(Order.Month %in% 1:10) %>%
group_by(Order.Year) %>% summarise(ord = n())
Order_holiday <- df %>% filter(Order.Month %in% 11:12) %>%
group_by(Order.Year) %>% summarise(ord1= n())
Pre_holiday <- Order_preholiday$ord
Holiday <- Order_holiday$ord1
Years <- c("2014", "2015", "2016", "2017")
df_growthorder <- data.frame(Pre_holiday, Holiday, Years)
df_growthorder2 <- melt(df_growthorder, id.vars='Years')
plot_hol <- ggplot(df_growthorder2, aes(x=Years, y=value, fill=variable)) +
geom_bar(stat='identity', position='dodge') +
labs(title="Orders Pre-Holiday vs Holiday", x = "Years", y="Orders") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_fill_manual(values = c("#da6474", "#80b1d3", "#fdb462", "#7fc97f" ))
################################################################################
require(gridExtra)
grid.arrange(plot_year, plot_hol, ncol = 2, nrow = 1)
```
Similar to the analysis carried out before, we can check how sales and profits generated by each category behave over the years. The first thing that catches our attention is the fact that the profit has increased over the years for the *Office Supply* and *Technology* categories, but not for *Furniture*, for which it has fluctuated around the same value. However, sales generally show a tendency to increase over the years. Both *Office Supplies* and *Technology* have very similar behavior.
```{r, message = FALSE, fig.height=14, fig.width=32, dev = "png", dpi = 300}
Technology_sales <- df %>% filter(str_detect(Category, 'Technology')) %>%
group_by(Order.Year) %>% summarise(Sales_technology = sum(Sales))
Technology_profit <- df %>% filter(str_detect(Category, "Technology")) %>%
group_by(Order.Year) %>% summarise(Profit_technology = sum(Profit))
Years <- c("2014", "2015", "2016", "2017")
Sales <- Technology_sales$Sales_technology
Profit <- Technology_profit$Profit_technology
df_technology_sp <- data.frame(Sales, Profit, Years)
df_technology_sp2 <- melt(df_technology_sp, id.vars="Years")
plot_technology <- ggplot(df_technology_sp2, aes(x=Years, y=value, fill=variable)) +
geom_bar(stat="identity", position="dodge") +
labs(title="Sales and Profit for Technology", x = "Years", y="USD") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_fill_manual(values = c("#da6474", "#80b1d3", "#fdb462", "#7fc97f" ))
############################################################################
Furniture_sales <- df %>% filter(str_detect(Category, 'Furniture')) %>%
group_by(Order.Year) %>% summarise(Sales_furniture = sum(Sales))
Furniture_profit <- df %>% filter(str_detect(Category, "Furniture")) %>%
group_by(Order.Year) %>% summarise(Profit_furniture = sum(Profit))
Profit <- Furniture_profit$Profit_furniture
Sales <- Furniture_sales$Sales_furniture
df_furniture_sp <- data.frame(Sales, Profit, Years)
df_furniture_sp2 <- melt(df_furniture_sp, id.vars="Years")
plot_furniture <- ggplot(df_furniture_sp2, aes(x=Years, y=value, fill=variable)) +
geom_bar(stat="identity", position="dodge") +
labs(title="Sales and Profit for Furniture", x = "Years", y="USD") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_fill_manual(values = c("#da6474", "#80b1d3", "#fdb462", "#7fc97f" ))
#############################################################################
Office_supplies_sales <- df %>% filter(str_detect(Category, 'Office Supplies')) %>%
group_by(Order.Year) %>% summarise(Sales_office_supplies = sum(Sales))
Office_supplies_profit <- df %>% filter(str_detect(Category, "Office Supplies")) %>%
group_by(Order.Year) %>% summarise(Profit_office_supplies = sum(Profit))
Profit <- Office_supplies_profit$Profit_office_supplies
Sales <- Office_supplies_sales$Sales_office_supplies
df_office_supplies_sp <- data.frame(Sales, Profit, Years)
df_office_supplies_sp2 <- melt(df_office_supplies_sp, id.vars="Years")
plot_office <- ggplot(df_office_supplies_sp2, aes(x=Years, y=value, fill=variable)) +
geom_bar(stat="identity", position="dodge") +
labs(title="Sales and Profit for Office Supplies", x = "Years", y="USD") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_fill_manual(values = c("#da6474", "#80b1d3", "#fdb462", "#7fc97f" ))
################################################################################
require(gridExtra)
grid.arrange(plot_technology, plot_furniture, plot_office, ncol = 3, nrow = 1)
```
[cell below]
Following we will analyze four plots that would help us understand how the profit changes for different categories, regions and segments as well as the relation between discount and quantity bought.
```{r, message = FALSE, fig.height=28, fig.width=32, dev = "png", dpi = 300}
df1 <- df %>% group_by(Segment,Category) %>% summarise(n=median(Profit))
plot1 <- ggplot(df1, aes(Segment, Category, fill=n))+
scale_fill_distiller( direction = 1)+ geom_tile(color='white')+
geom_text(aes(label=paste(round(n,0),'$')), color = 'black', size=10)+
labs(title='', fill='Median Profit') + theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 16, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28))
################################################################################
df2 <- df %>% group_by(Region,Category) %>% summarise(n=median(Profit))
plot2 <- ggplot(df2, aes(Region, Category, fill=n))+
scale_fill_distiller( direction = 1)+ geom_tile(color='white')+
geom_text(aes(label=paste(round(n,0),'$')), color = 'black', size=10)+
labs(title='', fill='Median Profit') + theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 16, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28))
################################################################################
# df3 <- df %>% mutate(Discount = cut_width(Discount,0.2,boundary=0))
df3 <- df %>% mutate(Discount = cut(Discount, c(0, 0.1, 0.2, 0.8), include.lowest = TRUE))
df3 <- df3 %>% group_by(Discount, Sub.Category) %>% summarise(n = mean(Quantity))
plot3 <- ggplot(df3, aes(Discount, Sub.Category, fill= n))+
scale_fill_distiller( direction = 1) + geom_tile(color='white')+
geom_text(aes(label=paste(round(n,2))), color = 'black', size=10)+
labs(title='', x = "Discount", fill='Avg. Quantity') + theme_minimal() +
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 16, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28))
################################################################################
df4 <- df %>% mutate(Discount = cut_width(Discount,0.15,boundary=0))
df4 <- df4 %>% group_by(Discount)
plot4 <- ggplot(df4, aes(x=Discount, y= Profit, fill = Category))+
geom_bar(stat = "identity", position = "stack") + labs(title="", x="Discount", y="Profit") +
theme_minimal()+
theme(axis.text=element_text(size=24), axis.title.x = element_text(size = 28),
axis.title.y = element_text(size = 28),
plot.title = element_text(size = 16, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
scale_y_continuous(label = scales::dollar) +
scale_fill_manual(values = c("#da6474", "#80b1d3", "#fdb462", "#7fc97f" )) +
geom_hline(yintercept=0, linetype="dashed")
################################################################################
require(gridExtra)
grid.arrange(plot1, plot2, plot3, plot4, ncol = 2, nrow = 2)
```
**Top left**<br>
The median profit generated by each segment oscillates around the same value for each category, and is much bigger for *Technology* than for *Office Supplies* and *Furniture*.
**Top right**<br>
West is the region where the median profit is highest, although in South both *Technology* and *Furniture* present the same median values. For the Central region, *Furniture* has a negative median profit and *Office Supplies* shows the smallest positive median profit across all regions and categories.
**Bottom left**<br>
For some subcategories there is no difference in the quantity bought whether there is a discount or not; clients buy the same quantity on average. For other subcategories, like *Binders*, *Bookcases* and *Fasteners* the quantity bought tends to increase with an increasing discount.
**Bottom right**<br>
Profit changes when a discount is applied and we can observe that from 30% discount the profit starts turning negative.
### Top 10 clients analysis
A study of the best and worst clients for the store is important to understand how to maximize the profits and take care of the clients, but also to know how to minimize the losses. The first barplot represents the top-10 clients according to purchases over the four years. The amount of orders they made is around 30, being the customer with client ID *WB-21850* the one that more orders has made. These clients make most of their purchases on the office supplies category. Also, 6 out of 10 of these clients are *Consumer* type of client.
Next step is to analyze the top-10 clients that generate more profit and more losses (middle left and right barplots respectively). The "most profitable" clients generate around 5000 USD each, being *TC-20980* (*Corporate*) the best client according to profit generation. Most of their purchases are on the technology category for some clients and office supplies for others. Six out of ten of these clients belong to the *Consumer* segment.
Clients that generate the largest negative profit cause losses that range from 2000 to 6500 USD approximately. By far, the client that causes the more losses is *CS-12505* (*Consumer*). As with the most profitable clients, the losses are usually related to the technology and office supplies categories. Only two of these clients are from the *Home Office* segment, four from the *Consumer* segment and four from the *Corporate* segment.
We can observe that the top-10 clients according to orders made, generate in general less than 5 times the profit that the most "profitable" clients generate. In fact, some of them generate negative profit. This is important to check, because it's not profitable to have a client that makes many purchases but at the end causes losses.
Finally, we plot the top-10 clients that more money spend. It is remarkable to see that none of the clients that generate the more profit is in the list of clients that more money spend. There is one client in this list however, that is also in the top-10 clients that more purchases have made. This client is the one who more money has spent over the four years and he/she belongs to the *Corporate* segment.
```{r, message = FALSE, fig.height=32, fig.width=32, dev = "png", dpi = 300}
top_buyers <- tail(names(sort(table(df$Customer.ID))), 10)
df_top_buyers <- df %>% filter(df$Customer.ID %in% top_buyers)
segment_purch <- df_top_buyers %>% group_by(Customer.ID, Segment) %>%
summarize(Sales = sum(Sales), Profit = sum(Profit), Number.Orders = n())
#kable(segment_purch[1:10,])
segment_purch[1:10,] %>%
kable() %>%
kable_styling(full_width = F)
plot_top <- ggplot(df_top_buyers, aes(x = Customer.ID, fill = Category)) +
geom_bar(position = "stack",bins = 10) +
labs(x = "Clients", y="Orders") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.text.x = element_text(angle=45),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28), plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
ggtitle("Top 10 clients according to purchases") +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))
################################################################################
plot_top_profit <- ggplot(df_top_buyers, aes(x = Customer.ID, y = Profit, fill = Category)) +
geom_bar(stat="identity", position = "stack", bins = 10) +
labs(x = "Clients", y="Profit") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.text.x = element_text(angle=45),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
ggtitle("Top 10 clients according to purchases") +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))+
scale_y_continuous(label = scales::dollar)+
geom_hline(yintercept=0, linetype="dashed")
################################################################################
df_profit <- df %>% group_by(Customer.ID) %>% summarise(prof = sum(Profit))
df_profit <- df_profit[order(df_profit$prof),]
top_profit_neg <- head(df_profit$Customer.ID, 10)
top_profit_pos <- tail(df_profit$Customer.ID, 10)
df_top_pos <- df %>% filter(Customer.ID %in% top_profit_pos)
segment_prof_pos <- df_top_pos %>% group_by(Customer.ID, Segment) %>%
summarize(Sales = sum(Sales), Profit = sum(Profit), Number.Orders = n())
segment_prof_pos[1:10,] %>%
kable() %>%
kable_styling(full_width = F)
plot_top_pos <- ggplot(df_top_pos, aes(x = Customer.ID, y = Profit, fill = Category)) +
geom_bar(stat="identity", position = "stack", bins = 10) +
labs(x = "Clients", y="Profit") +
theme_minimal() +
theme(axis.text=element_text(size=24), axis.text.x = element_text(angle=45),
axis.title.x = element_text(size = 28), axis.title.y = element_text(size = 28),
plot.title = element_text(size = 38, hjust = 0.5),
legend.text = element_text(size = 24), legend.title = element_text(size=28)) +
ggtitle("Top 10 clients with net positive profit") +
scale_fill_manual(values = c("#da6474","#80b1d3", "#fdb462", "#7fc97f"))+
scale_y_continuous(label = scales::dollar)+
geom_hline(yintercept=0, linetype="dashed")
################################################################################
df_top_neg <- df %>% filter(df$Customer.ID %in% top_profit_neg)
segment_prof_neg <- df_top_neg %>% group_by(Customer.ID, Segment) %>%
summarize(Sales = sum(Sales), Profit = sum(Profit), Number.Orders = n())
segment_prof_neg[1:10,] %>%
kable() %>%
kable_styling(full_width = F)