LAB 5

Author

Andrea Davila

library(ggplot2)
data("diamonds")
head(diamonds)
# A tibble: 6 × 10
  carat cut       color clarity depth table price     x     y     z
  <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.23 Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43
2  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
3  0.23 Good      E     VS1      56.9    65   327  4.05  4.07  2.31
4  0.29 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63
5  0.31 Good      J     SI2      63.3    58   335  4.34  4.35  2.75
6  0.24 Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48
#cut and clarity
#z and depth
options(scipen=999) 
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.3     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ lubridate 1.9.2     ✔ tibble    3.2.1
✔ purrr     1.0.2     ✔ tidyr     1.3.0
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(socviz)
library(datasetsICR)

PART 1: Practice using pipes (dplyr) to summarize data: Two Categorical Variables

# Use `dplyr` to summarize the data by the two categorical variables and get the frequency and percent
summary_data <- diamonds %>%
  group_by(cut, clarity) %>%
  summarise(frequency = n()) %>%
  mutate(percent = frequency / sum(frequency) * 100)
`summarise()` has grouped output by 'cut'. You can override using the `.groups`
argument.
summary_data
# A tibble: 40 × 4
# Groups:   cut [5]
   cut   clarity frequency percent
   <ord> <ord>       <int>   <dbl>
 1 Fair  I1            210  13.0  
 2 Fair  SI2           466  28.9  
 3 Fair  SI1           408  25.3  
 4 Fair  VS2           261  16.2  
 5 Fair  VS1           170  10.6  
 6 Fair  VVS2           69   4.29 
 7 Fair  VVS1           17   1.06 
 8 Fair  IF              9   0.559
 9 Good  I1             96   1.96 
10 Good  SI2          1081  22.0  
# ℹ 30 more rows

Interpretations

Based on the visualization, we can see the percentage breakdown of diamonds by cut type (Fair, Good, Very Good, Premium, Ideal) and clarity rating. The clarity rating is represented by the colored bars, with higher clarity diamonds in darker colors. there is a correlation between diamond cut quality and clarity. Higher quality cut types like Premium and Ideal have a greater proportion of higher clarity stones. The lower quality cuts tend to have mostly lower clarity diamonds. This aligns with expectations - jewelers likely select the highest clarity rough diamonds to produce high quality Ideal and Premium cut gemstones. Lower clarity stones may end up in simpler, less precisely cut shapes. The visualization and distributions make intuitive sense based on the economics of diamond production and cutting.

PART 2: Create stacked and dodged bar charts: Two Categorical Variables

# Plot the two categorical variables as stacked bar chart
stacked_plot <- ggplot(summary_data, aes(x = cut, y = percent, fill = clarity)) +
  geom_bar(stat = "identity") +
  labs(title = "Stacked Bar Chart of Diamonds by Cut and Clarity",
       x = "Cut", y = "Percent",
       caption = "Data source: ggplot2, diamonds") +  # Adding caption mentioning data source
  theme_minimal()

stacked_plot

# Plot the two categorical variables as a dodged bar chart
dodged_plot <- ggplot(summary_data, aes(x = cut, y = percent, fill = clarity)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Dodged Bar Chart of Diamonds by Cut and Clarity",
       x = "Cut", y = "Percent",
       caption = "Data source: ggplot2, diamonds") +  # Adding caption mentioning data source
  theme_minimal()

dodged_plot

# Plot the two categorical variables as a faceted horizontal bar chart without a legend
faceted_plot <- ggplot(summary_data, aes(x = cut, y = percent, fill = clarity)) +
  geom_bar(stat = "identity") +
  labs(title = "Faceted Horizontal Bar Chart of Diamonds by Cut and Clarity",
       x = "Percent", y = "",
       caption = "Data source: ggplot2, diamonds") +  # Adding caption mentioning data source
  facet_wrap(~ clarity, ncol = 1, strip.position = "bottom") +
  theme_minimal() +
  theme(legend.position = "none")

faceted_plot

PART 3: Practice using pipes (dplyr) to summarize data: Two Continuous Variables and One Categorical

library(dplyr)

# Summarize the data by 'cut' and calculate mean for 'z' and 'depth'
summarize_data <- diamonds %>%
  group_by(cut) %>%
  summarise(mean_z = mean(z),
            mean_depth = mean(depth))
summarize_data
# A tibble: 5 × 3
  cut       mean_z mean_depth
  <ord>      <dbl>      <dbl>
1 Fair        3.98       64.0
2 Good        3.64       62.4
3 Very Good   3.56       61.8
4 Premium     3.65       61.3
5 Ideal       3.40       61.7

Interpretations

The specifics of the dataset and the context of the variables under study will determine whether or not the results make sense. When ‘z’ denotes a diamond’s depth and ‘depth’ denotes the overall depth percentage, for instance, it makes sense to anticipate variations in these values among various ‘cut’ categories. Understanding how the mean “z” and “depth” values change with different diamond cuts may be gained from the summarized data.

PART 4: Create a scatterplot: Two Continuous Variables and One Categorical

scatterplot <- ggplot(diamonds, aes(x = z, y = depth, color = cut)) +
  geom_point(size = 5) +
  annotate(geom = "text", x = 1.6, y = 58, 
           label = "Two Continuous Variables and One Categorical", hjust = 0) +
  labs(y = "Depth", x = "z", 
       title = "Scatterplot of Diamonds: z vs. Depth", 
       subtitle = "z has a higher percentage than depth",
       caption = "ggplot2, diamonds")

scatterplot

PART 5: Legends and guides

scatterplot_modified <- ggplot(diamonds, aes(x=z, y=depth, color=cut)) +
geom_point(size=5) +
    annotate(geom = "text", x = 1.6, y=58, 
                     label = "Scatterplot of Diamonds: z vs. Depth", hjust=0) +
    labs(y="Depth", x="z", 
         color = "cut",
         title="Scatterplot of Diamonds: z vs. Depth", 
         subtitle = "z has a higher percentage than depth",
         caption = "ggplot2, diamonds",
         caption <- "ggplot2, diamonds") +
  theme(legend.title = element_text(color="gray50", size=14, face="bold"),
        legend.position = c(x=0.1, y=.7)) 
scatterplot_modified

PART 6: Data Labels

scatterplot_modified2 <- ggplot(diamonds, aes(x=z, y=depth, color=cut)) +
geom_point(size=5) +
    geom_text(mapping = aes(label=cut), hjust=1.2, size=3) +
    annotate(geom = "text", x = 1.6, y=58, 
                     label = "Scatterplot of Diamonds: z vs. Depth", hjust=0) +
    labs(y="Depth", x="z", 
         title="Scatterplot of Diamonds: z vs. Depth", 
          subtitle = "z has a higher percentage than depth",
         caption = "ggplot2, diamonds",
         color = "Cut") +
    theme(legend.position = "none")
scatterplot_modified2

PART 7: Interpretation

Part 4 chart insights

The R code utilizes ggplot2 to construct an insightful scatterplot visualization of the diamonds dataset by mapping the numeric attributes “z” and “depth” to x/y axes and encoding the categorical “cut” variable through color, employing layers of geom_point and annotations to promote clarity in examining the interactions between these diamond characteristics, leveraging ggplot2’s grammar of graphics flexibility to provide a structured and customizable foundation for iterative data visualization and further statistical analysis of the dataset.

Part 5 chart insights

By continuing to map the numeric attributes z and depth to x/y positions while coloring points based on the categorical cut variable, the visual foundation holds to explore relationships between diamond dimensions and quality. Enhancements come through tweaking textual annotations for clarity, adjusting legend styling and position to be more visually prominent, and customizing multi-layered titles to further document insights the visualization aims to convey around variability of attributes. By iterating on an initial scatterplot visualization via ggplot2’s flexible grammar of graphics, the code promotes structured and customizable data exploration to sharpen understanding of interactions in the diamonds data through purposeful visualization updates. The multifaceted nature of the plot enables drawing observers into nuanced analysis, facilitated by the code enhancements that tune visual styling choices alongside the core geometric mappings.

Part 6 chart insights

The provided code further builds on the previous diamond scatterplot visualization using ggplot2, retaining the mapping of numeric attributes z and depth to plot positions and the color encoding based on categorical cut quality. Enhancements come in the form of layered geoms like geom_text to directly label points by cut category right on the plot, reducing reliance on a legend. The text annotation and structured captions also remain to document insights. By programatically removing the legend via the theme adjustment while labeling points directly, the code continues iterative development to draw attention to diamond cuts and how they may link to dimensions. Removal of the legend also reduces visual clutter. Overall, the multifaceted scatterplot visualization continues to become more focused and refined through small but meaningful tweaks that simplify the plot while retaining core geometric mappings to highlight key relationships between variables. The code promotes both understanding of the diamonds data itself through purposeful visualization, as well as serving as an example of iterative development to construct more tailored and insightful data graphics.