Showing posts with label Analytics. Show all posts
Showing posts with label Analytics. Show all posts

Wednesday, August 10, 2022

Brief Reviews On Data Visualization and Multicollinearity: A Humble Take On The Current Landscape

Hello. For this post, I thought it might be prudent to cite two articles and critique them. The first article is concerned with Boxplots, and the second has to do with multicollinearity. 


The goal of this exercise is to read an article regarding any matter of data analytics, digest the article, and offer a reaction to the authors. 


In this exercise, there is a need to think critically about the topic, and how to utilize the information to become a better data analyst. 


I hope this helps! 



 “Why Is a Boxplot Better Than a Histogram?” 


Click here for source.


The fundamental concept behind this article is to plot your data BEFORE you do any sort of analysis of the data. But how should you plot the data? What type of visualization should one use at the initial stage of their analysis? 


The author of this article argues that boxplots should be the preferred standard to visualization data, and that histograms—although most commonly used—present relationships in the data that can be misinterpreted. The author proposes that boxplots can be a remedy to misinterpretations that histograms may account for. 


This is the main goal, or thesis of this article.

 

Specifically, boxplots have several advantages when it comes to visualizing data. Along with being able to plot multiple sets of data at once, boxplots can show outliers, imply the distributions of the sets—including whether the data is normal or skewed. 


Unlike histograms, boxplots are adept at showing the median, first and third quartiles, and the minimum and maximum approximation of a total range. To be clear, histograms do show this information as well, but there is much more guess work involved as the values can only be approximated upon visual inspection. 


Finally, boxplots are easier to read and interpret compared to histograms.

 

After reading this article, it is clear that the author prefers to use boxplots over histograms because of its clear advantages. Noting the rationale for boxplots, I am going to begin using boxplots in my analysis, but before I yield to the author’s suggestion, I would like to make an argument that favors the ease of use for histograms. 


In the early stages of analysis, I feel that one should be concerned about both the quality and the quantity of information is appropriate for that specific stage. Let me explain.


Let’s assume that a business manager or supervisor gives their subordinate the task of fitting a regression line through a set of observations. Let’s also assume that this task uses data sets that are primarily numerical, and that there are very few categorical variables of interest. 


We might also assume that this task might be industry-specific; data sets that encompass customer profiles in banking might be different than data sets that encapsulate patient medical history. 


With this in mind, I argue that depending on the STAGE (Exploratory Data Analysis, for instance) of the analysis and the TYPE of data sets that are use, there might be a preference for the ease and simplicity of a histogram. 


If I already know, based on prior professional experience, that a regression analysis is the goal, then I might not need to know the total range of a data set (first and third quartile, median, minimum and maximum) until further into my analysis. 


Consequently, it might be preferable to run a “proc means” (in SAS) or a “summary ()” function (in R) to determine a more accurate account of those descriptive statistics. If my goal is to determine correlation between my response and explanatory variables of interest, then a quick check with a histogram might be a simpler approach, as I don’t require the additional information of a boxplot, yet. 


Boxplots are not useful visualizations for describing a correlation between two variables, and that is why I would use a histogram IN THE EARLY stages of an analysis. 


In all fairness, the author of the article DOES make the point—almost too briefly—that boxplots can also be used alongside of a histogram to provide richer details about data in question. 


This might be a practical approach, and it might require more effort to code into the statistical software, but it could be worth the effort if the output provides a more meaningful account of what is happening in the data. 


For my own approach to analysis, it would make sense for me to explore boxplots more closely to see if I can reach an agreement with the author. At the moment, I am most familiar with regression analysis, so histograms serve my initial goal of determining correlation between my response and explanatory variables. 


Yet, there are other algorithms and methods that are used in data analysis and machine learning, like classification and clustering methods, which require a different mindset; the problems that these additional methods solve is different than regression.

 

 

“Multicollinearity in Regression Analysis: Problems, Detections and Solutions,” by Jim Frost. 


Click here for source. 


What is multicollinearity, and why is it an issue in regression analysis? Statistics professional and thought leader, Jim Frost, says that multicollinearity occurs when explanatory variables in a regression model are highly correlated. This can cause concern as explanatory variables are supposed to be independent of one another. 


In this article, Frost’s main point is to show analysts how to detect multicollinearity between explanatory variables, and finally how to resolve issues of multicollinearity.

 

One can make the claim that one of the most important goals of a regression analysis is to “isolate the relationship between” the response variable and the explanatory variables. And since this goal is so vital to this type of analysis, it is logical to conclude that multicollinearity would present an issue in regression; if an explanatory variable is acting similar to the response variable, then there is an issue that needs to be corrected. 


If an analyst decides that a Multiple Linear Regression is the best approach to making a prediction based on the data, they need to be confident that every 1 unit increase in variable Beta 1—given that all other variables are held constant—will result in a change in the response variable. 


But this can’t happen if independent variables display multicollinearity with other independent variables. At that point, the regression model is almost completely useless!

 

Frost suggests that there are two key issues with multicollinearity. The first issue is that beta coefficients can have a “high sensitivity to change.” Meaning that x-variables can be extreme—high or low—and such severe values can lead to an inaccurate prediction model. 


Second, since multicollinear values can have extreme beta coefficients, there could be a miscalculation in the statistical significance (p-values) of the variables in the final model. And for this reason, an analyst can NOT trust these levels of significance. 


So then, how does an analyst address issues of multicollinearity? Frost argues that there are methods to fix these issues, but boldly suggests that issues of multicollinearity depend heavily on the “primary goal of the regression analysis.” 


Frost proposes that moderate multicollinearity might not need to be resolved, as the severity of a moderate position might not impact the regression model. Although, this approach—or neglect—should only be assessed on a case-by-case basis. Also, he posits that variables that have a multicollinear relationship might not be included in the final model, and therefore, do NOT need to be addressed early on.  


Yet, for analysts that are conservative and meticulous, there is such a test method called Variance Inflation Factors, or VIF. In the modeling process, VIF can be used to determine the strength of correlation between independent variables, and with scores above a certain threshold, these values can be removed from the prediction model. 


In my own analysis, I have been taught to use VIF metrics to determine which explanatory variables to remove during the modeling process. 


Also, I use the Adjusted R-Square score compared to the R-Square score, as this metric provides a more meaningful measure of predictability—penalizing models that rely on a large quantity of variables at the expense of statistical significance.


With the combination of VIF metrics, to remove variables, and relying on an Adjusted R-Square score, I feel confident that I can create a model that is, at the very least, a conservative estimation of future response values. 


Since I am not a highly skilled analyst (yet), I will be meticulous and remove variables that the VIF method highlights. The author Jim Frost is not the only analytics thought leader to exude a “it depends on the data/situation” mentality. 


For him, he is more astute at analytics, therefore, he is more skilled at determining which variables to remove, and which to leave in the model. I am not at his level of preeminence, so for now, I will remove any variable with the smallest hint of multicollinearity.  

Share:

Clustering Analysis of Universities: Schools in Alabama, California, and Florida According to SAT Averages and Admission Rates

Thank you for checking out my post on Clustering earlier last week. I wanted to expanded on the method with an exercise on clustering universities in the states of Alabama, California, and Florida. I hope you have fun with this one. I know I did!


Let’s begin by loading packages, setting our directory and loading our data set. We will be using the “colleges” data set created by the US Department of Education, and cleaned by Fred Nwanganga and Mike Chapple.


As always, if you wish to follow along, you can download the data set on the Google Drive by clicking on the "Data Sets" tab on the homepage. And like all of my other posts, the code that you can replicate is highlighted in BLUE.


library(tidyverse)

## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --

## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.4     v dplyr   1.0.7
## v tidyr   1.1.3     v stringr 1.4.0
## v readr   2.0.1     v forcats 0.5.1

## Warning: package 'stringr' was built under R version 4.1.2

## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

setwd("C:/Users/firstnamelastinitial/OneDrive/Documents/R")

college <- read_csv("college.csv", col_types = "nccfffffnnnnnnnnn")


Let’s take the time to do some fundamental exploratory data analysis:


dim(college)

## [1] 1270   17

str(college)

## spec_tbl_df [1,270 x 17] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ id                : num [1:1270] 102669 101648 100830 101879 100858 ...
##  $ name              : chr [1:1270] "Alaska Pacific University" "Marion Military Institute" "Auburn University at Montgomery" "University of North Alabama" ...
##  $ city              : chr [1:1270] "Anchorage" "Marion" "Montgomery" "Florence" ...
##  $ state             : Factor w/ 51 levels "AK","AL","AR",..: 1 2 2 2 2 2 2 2 2 2 ...
##  $ region            : Factor w/ 4 levels "West","South",..: 1 2 2 2 2 2 2 2 2 2 ...
##  $ highest_degree    : Factor w/ 4 levels "Graduate","Associate",..: 1 2 1 1 1 1 1 1 1 1 ...
##  $ control           : Factor w/ 2 levels "Private","Public": 1 2 2 2 2 2 2 1 2 2 ...
##  $ gender            : Factor w/ 3 levels "CoEd","Women",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ admission_rate    : num [1:1270] 0.421 0.614 0.802 0.679 0.835 ...
##  $ sat_avg           : num [1:1270] 1054 1055 1009 1029 1215 ...
##  $ undergrads        : num [1:1270] 275 433 4304 5485 20514 ...
##  $ tuition           : num [1:1270] 19610 8778 9080 7412 10200 ...
##  $ faculty_salary_avg: num [1:1270] 5804 5916 7255 7424 9487 ...
##  $ loan_default_rate : num [1:1270] 0.077 0.136 0.106 0.111 0.045 0.062 0.096 0.007 0.103 0.063 ...
##  $ median_debt       : num [1:1270] 23250 11500 21335 21500 21831 ...
##  $ lon               : num [1:1270] -149.9 -87.3 -86.3 -87.7 -85.5 ...
##  $ lat               : num [1:1270] 61.2 32.6 32.4 34.8 32.6 ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   id = col_number(),
##   ..   name = col_character(),
##   ..   city = col_character(),
##   ..   state = col_factor(levels = NULL, ordered = FALSE, include_na = FALSE),
##   ..   region = col_factor(levels = NULL, ordered = FALSE, include_na = FALSE),
##   ..   highest_degree = col_factor(levels = NULL, ordered = FALSE, include_na = FALSE),
##   ..   control = col_factor(levels = NULL, ordered = FALSE, include_na = FALSE),
##   ..   gender = col_factor(levels = NULL, ordered = FALSE, include_na = FALSE),
##   ..   admission_rate = col_number(),
##   ..   sat_avg = col_number(),
##   ..   undergrads = col_number(),
##   ..   tuition = col_number(),
##   ..   faculty_salary_avg = col_number(),
##   ..   loan_default_rate = col_number(),
##   ..   median_debt = col_number(),
##   ..   lon = col_number(),
##   ..   lat = col_number()
##   .. )
##  - attr(*, "problems")=<externalptr>


colnames(college)

##  [1] "id"                 "name"               "city"             
##  [4] "state"              "region"             "highest_degree"   
##  [7] "control"            "gender"             "admission_rate"   
## [10] "sat_avg"            "undergrads"         "tuition"          
## [13] "faculty_salary_avg" "loan_default_rate"  "median_debt"      
## [16] "lon"                "lat"


There are a total of 1270 rows, and 17 columns. We can confirm the data types with this function. There are 17 variables.


This time, we will do our clustering analysis on the state of Alabama. So let’s create a new data set with ONLY schools from this state.


alabama_schools <- college %>%
  filter(state == "AL") %>%
  column_to_rownames(var = "name")


After we pass the state code “MD” in the filter() function, we use the column_to_rowname() function which allows us to see the name of the school for our observations. Let’s view the new data set:


View(alabama_schools)


We now have 24 observations, or schools, and 16 variables in our new data set with only schools from Maryland. Now, let’s use the select() function to specify which features we are interested in. 


For this case, we are interested in admission_rate and sat_avg. Sorry for making that decision for you!! 


alabama_schools %>%
  select(admission_rate, sat_avg) %>%
  summary()

##  admission_rate      sat_avg   
##  Min.   :0.4414   Min.   : 811 
##  1st Qu.:0.5309   1st Qu.: 969 
##  Median :0.5927   Median :1035 
##  Mean   :0.6523   Mean   :1033 
##  3rd Qu.:0.8064   3rd Qu.:1109 
##  Max.   :1.0000   Max.   :1219


Before moving on, I would like to observe that we are using the pipe (%>%) operator which allows us to compose cleaner code. Let’s move on:


As expected, we can notice that the range of values between both variables have vastly different ranges. As a reminder, we MUST normalize our variables BEFORE building our model.


alabama_schools_scaled <- alabama_schools %>%
  select(admission_rate, sat_avg) %>%
  scale()


We create a new object, using our alabama_schools data set, that utilizes the scale() function to “normalize” our data to z-scores. This creates an optimal scenario to enable us to use a clustering model.


Let’s see the new values for each variable by piping the summary() function into our new data object.


alabama_schools_scaled %>%
  summary()

##  admission_rate       sat_avg       
##  Min.   :-1.3758   Min.   :-1.92418 
##  1st Qu.:-0.7922   1st Qu.:-0.55343 
##  Median :-0.3884   Median : 0.01916 
##  Mean   : 0.0000   Mean   : 0.00000 
##  3rd Qu.: 1.0051   3rd Qu.: 0.66332 
##  Max.   : 2.2685   Max.   : 1.61547


Our variables have been standardized to z-scores and our data is officially normalized. Remember, by normalizing our data we don’t need to worry about extreme differences between our variables. Let’s load the stats package so we can run the algorithm.


Let’s set the seed so we can have reproducible results.


library(stats)

set.seed(1234)


Notice that we have set our seed to randomize the data. Simply remember the number that you use in the argument so that you can reproduce the results every time you run this algorithm.


Reminder:


The kmeans() functions takes three arguments. Our scaled data set, which recall is alabama_schools_scaled, is the first argument. Centers will determine how many cluster centers we will have. This is essentially our k-value. We are going to set our centers (k-value) to 3, because we want three clusters. The nstart will be set to 25, and this will be the total number of configuration attempts. Let’s run it!


k_3 <- kmeans(alabama_schools_scaled, centers = 3, nstart = 25)


Great! Let’s start to explore this cluster. Let’s see how many observations are in each of the three clusters.


k_3$size

## [1]  8  6 10


This output tells us that one cluster has 8 observations, another has 6 observations, and the third cluster has the remaining 10 observations.


We can also get a sense of the values of the three cluster centers by using the centers attribute.


k_3$centers

##   admission_rate    sat_avg
## 1     -0.6824578  0.5743977
## 2     -0.8282133 -1.2431427
## 3      1.0428942  0.2863675


Let’s break this down per cluster:


The first cluster center has a value of roughly -.68 for admission_rate and .57 for sat_avg.


The second cluster center has a value of roughly -.82 for admission_rate and -1.24 for sat_avg.


The third cluster center has a value of roughly 1.04 for admission_rate and approximately .28 for sat_avg.


THESE VALUES ARE NORMALIZED VALUES OF THE ORIGINAL DATASET!!!


With this in mind, we have lost some ability to interpret this part of the data. This is fine as our objective is to group these schools as accurately as possible.


What good is clustering if we can’t have a visualization of our model. Let’s load another package called factoextra.


library(factoextra)

## Warning: package 'factoextra' was built under R version 4.1.2

## Welcome! Want to learn more? See two factoextra-related books at https://goo.gl/ve3WBa


Next, will pass three arguments into a very powerful function called the fviz_cluster() function. The first argument will be an object where our model is stored, k_3. The second component in the function will be the data set, which is the scaled data set, alabama_schools_scaled. The last element of the function will contain a specification that will help organize our labels.


fviz_cluster(k_3, data = alabama_schools_scaled, repel = TRUE)

## Warning: ggrepel: 1 unlabeled data points (too many overlaps). Consider
## increasing max.overlaps


Alabama Schools Cluster


There is a lot to unpack here, but for brevity, I will describe the clusters as simply as possible.


Cluster 1 is labeled in red and as you can notice it contains schools that have the highest SAT average and lowest admission rates. I would argue that the 8 schools in this cluster are the most elite schools in Alabama as observed by the two metrics that we have used.


Cluster 2 is labeled in green. Universities in this cluster have the lowest SAT average, and are low in admission rates.


Cluster 3 is labeled in blue. Schools in this cluster have high admission rate and have high sat averages; this cluster is similar to cluster 1 with regards to high SAT scores.


I suppose all school clusters will have similar arrangements on two dimensional space if they are measured by same features, sat_avg and admission_rate. 


Let’s see the how the three clusters looks for the state of California, and Florida. Just to test out my hypothesis.


california_schools <- college %>%
  filter(state == "CA") %>%
  column_to_rownames(var = "name")



california_schools %>%
  select(admission_rate, sat_avg) %>%
  summary()

##  admission_rate      sat_avg     
##  Min.   :0.0509   Min.   : 871.0 
##  1st Qu.:0.4051   1st Qu.: 993.5 
##  Median :0.5800   Median :1086.0 
##  Mean   :0.5477   Mean   :1113.7 
##  3rd Qu.:0.7425   3rd Qu.:1222.0 
##  Max.   :0.8750   Max.   :1545.0

california_schools_scaled <- california_schools %>%
  select(admission_rate, sat_avg) %>%
  scale()



set.seed(1234)


k_3 <- kmeans(california_schools_scaled, centers = 3, nstart = 25)


fviz_cluster(k_3, data = california_schools_scaled, repel = TRUE)

## Warning: ggrepel: 58 unlabeled data points (too many overlaps). Consider
## increasing max.overlaps


California Schools Cluster

Now for Florida:


florida_schools <- college %>%
  filter(state == "FL") %>%
  column_to_rownames(var = "name")


florida_schools %>%
  select(admission_rate, sat_avg) %>%
  summary()

##  admission_rate      sat_avg   
##  Min.   :0.2286   Min.   : 803 
##  1st Qu.:0.4481   1st Qu.: 948 
##  Median :0.5188   Median :1065 
##  Mean   :0.5436   Mean   :1057 
##  3rd Qu.:0.6157   3rd Qu.:1153 
##  Max.   :1.0000   Max.   :1330

florida_schools_scaled <- florida_schools %>%
  select(admission_rate, sat_avg) %>%
  scale()



set.seed(1234)


k_3 <- kmeans(florida_schools_scaled, centers = 3, nstart = 25)


fviz_cluster(k_3, data = florida_schools_scaled, repel = TRUE)

## Warning: ggrepel: 19 unlabeled data points (too many overlaps). Consider
## increasing max.overlaps


Florida Schools Cluster


An observation that I would like to make is that the clusters are labeled different from graphic to graphic. For example, Alabama’s elite schools are labeled red, California’s elite schools are labeled color green, and Florida’s top schools are labeled blue.


Yet, regardless of how the cluster is labeled by color, we can deduce that elite level schools are positioned in the upper left portion of the quadrant.



THANK YOU!


Thank you so much reading this different take on Clustering. This machine learning method is used widely in a Marketing context, namely when managers are looking to categorize, or "segment," groups of costumers.


I am proud of all of you! I know that the steps that you are taking towards a safer, healthier life, are tedious, and at times cumbersome. 


But you know what? 


Your dedication to ridding yourselves of a toxic profession will pay off. You will live happier lives, filled with new found love from family and friends, and even acquaintances who are drawn to your hard work and professional ethic. 


Thank you for allowing me to be part of your journey to becoming data analysts, and data entrepreneurs. 


Share:

The Basics of Data Visualization: A Guide on GGplot2

I would like this post to be a demonstration on Data Visualization with the ggplot package. As you will discover, the package is adept at creating plots that are attractive and appealing. 


There won't be too much explanation on how to interpret these plots. I list a worthy resource for that at the conclusion of this post. Please look into it if this post inspires you.

I would like this post to go into the basics of ggplot2, which is a package that is meant to specialize in the visualization of data. I am using a book called “ggplot2: Elegant Graphics for Data Analysis,” by Hadley Wickham, as well as lecture material I have learned in class. 


I will use one of my favorite data sets called bikes, and the mpg data set later on, but I will not go into great details for this post. I want this post to show you how you can plot two numerical variables on the x and y-axis, and add appropriate labels to make this plot more interpretable.


As always, if you wish to follow along, please type the text that is highlighted in BLUE in your R Studio environment.


library(tidyverse)

## -- Attaching packages --------------------------------------- tidyverse 1.3.1 --

## v ggplot2 3.3.5     v purrr   0.3.4
## v tibble  3.1.4     v dplyr   1.0.7
## v tidyr   1.1.3     v stringr 1.4.0
## v readr   2.0.1     v forcats 0.5.1

## Warning: package 'stringr' was built under R version 4.1.2

## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

setwd("C:/Users/firstnamelastinitial/OneDrive/Documents/Fund of Bus Anal")
bikes <- read.csv("bikes.csv", header = TRUE)
str(bikes)

## 'data.frame':    731 obs. of  10 variables:
##  $ date       : chr  "2011-01-01" "2011-01-02" "2011-01-03" "2011-01-04" ...
##  $ season     : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ holiday    : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ weekday    : int  6 0 1 2 3 4 5 6 0 1 ...
##  $ weather    : int  2 2 1 1 1 1 2 2 1 1 ...
##  $ temperature: num  46.7 48.4 34.2 34.5 36.8 ...
##  $ realfeel   : num  46.4 45.2 25.7 28.4 30.4 ...
##  $ humidity   : num  0.806 0.696 0.437 0.59 0.437 ...
##  $ windspeed  : num  6.68 10.35 10.34 6.67 7.78 ...
##  $ rentals    : int  985 801 1349 1562 1600 1606 1510 959 822 1321 ...


So, I have loaded tidyverse, which contains ggplot2, and my data set. Now I would like to use ggplot to visualize variables within the bikes data frame. 


But first, allow me to summarize the basic format, or grammar, of the ggplot() function.


1.         You need a data frame.


2.         the second argument for this function requires a mapping aesthetic, or aes, which will have the variables you wish to see in graphical form.


3.         After you have satisfied these two arguments for the ggplot() function, you will need include a geom function, which follows a + sign.


Let me demonstrate what this may look like.


ggplot(bikes, aes(x = temperature, y = rentals))+
  geom_point()


Scatter Plot

Here is what that plot looks like. Throughout this post, I will use the same plot, but I will make it look more presentable, by making use of various functions and phrases. 


I hope that each iteration of this plot will give you an idea, and basic understanding of how ggplot is used, and its effectiveness in presenting your findings to your managers at your place of work.


Let’s change the color of the plot to blue.


ggplot(bikes, aes(x = temperature, y = rentals))+
  geom_point(colour = "blue")


Scatter Plot in Color



I would like to note that color and shape work well for categorical variables (non-numerical), and for continuous variables (numerical), size might be a better argument.


Now, it might be difficult to determine what type of relationship exists between the variables in our visualization. To me, it looks like there is a moderate (?) positive LINEAR (?) relationship between temperature and rentals. 


So, let’s test my hypothesis by superimposing a regression line over the data. We can do this with the geom_smooth() function, and inserting “lm” into “method” for our argument.


ggplot(bikes, aes(x = temperature, y = rentals))+
  geom_point()+
  geom_smooth(method = "lm")

## `geom_smooth()` using formula 'y ~ x'



Scatter Plot with Regression Line


My assumption that the variables in question have a linear relationship appears to have only some merit. Although, at this point, I don’t know how strong the correlation is. And now that I think about it, a linear model might NOT fit this data appropriately, as this line does not fit the outer extremities of our data too well. That is the subject of another post. Let’s continue.


In order to keep this post shorter, I want to touch quickly on how you can simply add labels to your graph. Please examine the following code, and note it’s output:


ggplot(bikes, aes(x = temperature, y = rentals))+
  geom_point(colour = "red")+
  geom_smooth(method = "lm")+
  labs(title = "Relationship Between Rentals and Temperature") +
  ylab("Rentals") +
  xlab("Temperature")

## `geom_smooth()` using formula 'y ~ x'



Scatter Plot with Regression Line 2


In our final input, we specified that the color of our observations will be red in the geom_point() function. We kept our Regression Line to give management an idea how a linear model might or might not be appropriate for our data set. This was specified in our geom_smooth() function. 


Lastly, we created a title for our graph called, “Relationship Between Rentals and Temperature.” We labeled our y-axis “Rentals” and this is our dependent variable. We labeled our x-axis “Temperature” and this will be our independent variable.


Let me do a comparison of both graphs so we can see how far we have come in our interpretation of the two variables in question.


ggplot(bikes, aes(x = temperature, y = rentals))+
  geom_point()



Scatter Plot


ggplot(bikes, aes(x = temperature, y = rentals))+
  geom_point(colour = "red")+
  geom_smooth(method = "lm")+
  labs(title = "Relationship Between Rentals and Temperature") +
  ylab("Rentals") +
  xlab("Temperature")

## `geom_smooth()` using formula 'y ~ x'


Scatter Plot

There are other ways that you can graph variables in ggplot, this goes without saying. Here are some other plots you can experiment with. To demonstrate these variations, I will use the mpg data set.


ggplot(mpg, aes(drv, hwy))+
  geom_jitter()



Plot

ggplot(mpg, aes(drv, hwy))+
  geom_boxplot()


Box Plot

ggplot(mpg, aes(drv, hwy))+

  geom_violin()


Violin Plot

You can find more information about the advantages and disadvantages of these plots in the book by Hadly Wickham, “ggplot2: Elegant Graphics for Data Analysis,” and I will not go into these elements for this post. I just wish to show you the potential of this powerful and useful package. Here is another plot that you can make:

ggplot(mpg, aes(displ, colour = drv))+
  geom_freqpoly(binwidth = 0.5)


Frequency Plot

You can explore this further in your own time.


To begin, pick two variables from your data set, try numerical values at first. Alter the default graphs color, add some sort of line to fit the data, and lastly, change the labels of the graph. 


THANK YOU!


I hope that this post gives you a quick solution for visualizing two variables on a plot, and also inspires you to go out and buy Hadley Wickham’s book, “ggplot2: Elegant Graphics for Data Analysis.”


Thank you so much for looking at this post. I hope it was helpful to you in your journey of becoming a data analyst, machine learning leader, or data entrepreneur.


Share: