Exploring Diamond Prices with dplyr and ggplot2

Author

Chanice Mckenzie

Introduction

This vignette demonstrates how to use dplyr and ggplot2 to summarize and visualize diamond prices. The example uses the diamonds dataset that comes with ggplot2, so no local files or external API requests are needed. Our question is: How does the relationship between diamond cut and price change when we also consider carat size?

1. Load packages and inspect the data

We load the packages used in this example. The diamonds dataset has one row per diamond, with information such as carat weight, cut quality, and price in US dollars.

library(dplyr)
library(ggplot2)
library(knitr)

diamonds_data <- ggplot2::diamonds

glimpse(diamonds_data)
Rows: 53,940
Columns: 10
$ carat   <dbl> 0.23, 0.21, 0.23, 0.29, 0.31, 0.24, 0.24, 0.26, 0.22, 0.23, 0.…
$ cut     <ord> Ideal, Premium, Good, Premium, Good, Very Good, Very Good, Ver…
$ color   <ord> E, E, E, I, J, J, I, H, E, H, J, J, F, J, E, E, I, J, J, J, I,…
$ clarity <ord> SI2, SI1, VS1, VS2, SI2, VVS2, VVS1, SI1, VS2, VS1, SI1, VS1, …
$ depth   <dbl> 61.5, 59.8, 56.9, 62.4, 63.3, 62.8, 62.3, 61.9, 65.1, 59.4, 64…
$ table   <dbl> 55, 61, 65, 58, 58, 57, 57, 55, 61, 61, 55, 56, 61, 54, 62, 58…
$ price   <int> 326, 326, 327, 334, 335, 336, 336, 337, 337, 338, 339, 340, 34…
$ x       <dbl> 3.95, 3.89, 4.05, 4.20, 4.34, 3.94, 3.95, 4.07, 3.87, 4.00, 4.…
$ y       <dbl> 3.98, 3.84, 4.07, 4.23, 4.35, 3.96, 3.98, 4.11, 3.78, 4.05, 4.…
$ z       <dbl> 2.43, 2.31, 2.31, 2.63, 2.75, 2.48, 2.47, 2.53, 2.49, 2.39, 2.…

2. Create useful categories with mutate() and case_when()

mutate() adds or changes columns without removing the original observations. case_when() assigns each diamond to a carat-size category. We use four non-overlapping ranges so diamonds are categorized consistently.

diamonds_clean <- diamonds_data |>
  mutate(
    carat_group = case_when(
      carat < 0.50 ~ "Under 0.50 ct",
      carat < 1.00 ~ "0.50–0.99 ct",
      carat < 1.50 ~ "1.00–1.49 ct",
      TRUE ~ "1.50 ct or more"
    ),
    carat_group = factor(
      carat_group,
      levels = c("Under 0.50 ct", "0.50–0.99 ct",
                 "1.00–1.49 ct", "1.50 ct or more")
    )
  )

# Check that every diamond belongs to a size group.
diamonds_clean |>
  count(carat_group) |>
  kable(caption = "Number of diamonds in each size group")
Number of diamonds in each size group
carat_group n
Under 0.50 ct 17674
0.50–0.99 ct 17206
1.00–1.49 ct 12825
1.50 ct or more 6235

3. Summarize price by cut with group_by() and summarise()

group_by() tells dplyr which observations to analyze together. summarise() reduces each group to summary statistics. We calculate both mean and median prices because unusually expensive diamonds may affect the mean. arrange() sorts the results from highest to lowest median price.

cut_summary <- diamonds_clean |>
  group_by(cut) |>
  summarise(
    diamonds = n(),
    mean_price = mean(price),
    median_price = median(price),
    .groups = "drop"
  ) |>
  arrange(desc(median_price))

cut_summary |>
  kable(digits = 0, caption = "Diamond prices summarized by cut")
Diamond prices summarized by cut
cut diamonds mean_price median_price
Fair 1610 4359 3282
Premium 13791 4584 3185
Good 4906 3929 3050
Very Good 12082 3982 2648
Ideal 21551 3458 1810

Interpretation: This table shows the unadjusted relationship between cut and price. Comparing cuts without accounting for diamond size can be misleading because a larger diamond typically costs more than a smaller one.

4. Compare cut within carat-size groups

We now group by both carat size and cut. This produces a more meaningful descriptive comparison than a single overall average, although other attributes (including color and clarity) can still differ within groups.

size_cut_summary <- diamonds_clean |>
  group_by(carat_group, cut) |>
  summarise(
    diamonds = n(),
    median_price = median(price),
    .groups = "drop"
  ) |>
  arrange(carat_group, desc(median_price))

size_cut_summary |>
  kable(digits = 0, caption = "Median diamond price by cut and carat-size group")
Median diamond price by cut and carat-size group
carat_group cut diamonds median_price
Under 0.50 ct Fair 113 830
Under 0.50 ct Ideal 8763 808
Under 0.50 ct Premium 4038 802
Under 0.50 ct Very Good 3557 661
Under 0.50 ct Good 1203 645
0.50–0.99 ct Very Good 4255 2422
0.50–0.99 ct Good 1791 2362
0.50–0.99 ct Premium 3562 2340
0.50–0.99 ct Ideal 6918 2241
0.50–0.99 ct Fair 680 2221
1.00–1.49 ct Ideal 4214 6323
1.00–1.49 ct Very Good 2896 5600
1.00–1.49 ct Premium 3952 5445
1.00–1.49 ct Good 1271 4899
1.00–1.49 ct Fair 492 4209
1.50 ct or more Ideal 1656 12720
1.50 ct or more Premium 2239 12364
1.50 ct or more Very Good 1374 12089
1.50 ct or more Good 641 10696
1.50 ct or more Fair 325 8938

5. Visualize comparisons with ggplot2

A boxplot shows the overall distribution of prices for each cut, including the median and variation. We hide individual outlier markers to keep the figure readable, but the underlying observations remain in the analysis.

ggplot(diamonds_clean, aes(x = cut, y = price)) +
  geom_boxplot(outlier.shape = NA, fill = "#83B6C9") +
  coord_cartesian(ylim = c(0, 12000)) +
  labs(
    title = "Diamond price distributions vary by cut",
    subtitle = "The overall comparison does not control for carat weight",
    x = "Cut quality",
    y = "Price (US dollars)",
    caption = "Source: ggplot2 diamonds dataset. Display clipped at $12,000; analysis uses all prices."
  ) +
  theme_minimal()

We can also use facet_wrap() to create a separate panel for each carat-size group. This helps us compare diamonds of more similar sizes while using a consistent y-axis across panels.

ggplot(size_cut_summary, aes(x = cut, y = median_price)) +
  geom_col(fill = "#397F96", width = 0.7) +
  facet_wrap(~ carat_group, ncol = 2) +
  scale_y_continuous(labels = scales::label_dollar()) +
  labs(
    title = "Comparing cuts within carat-size groups",
    subtitle = "Median price is calculated separately for each cut and size group",
    x = "Cut quality",
    y = "Median price (US dollars)",
    caption = "Source: ggplot2 diamonds dataset. Shared y-axis across panels."
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 35, hjust = 1))

6. Validate our summaries

A good analysis should include simple checks. The number of records in the cut summary should equal the number of rows in the original dataset, and every diamond should have a valid carat-size category.

stopifnot(sum(cut_summary$diamonds) == nrow(diamonds_data))
stopifnot(!anyNA(diamonds_clean$carat_group))
stopifnot(sum(size_cut_summary$diamonds) == nrow(diamonds_data))

cat("Checks passed: all observations are accounted for.\n")
Checks passed: all observations are accounted for.

Conclusion

This example demonstrates a common Tidyverse workflow: create variables with mutate() and case_when(), aggregate with group_by() and summarise(), rank with arrange(), and visualize with ggplot2. Looking at cut and price alone can obscure differences in diamond size; grouping by carat provides additional context. The results are descriptive, not causal: price may also depend on clarity, color, and other characteristics. A possible extension would use filter() or a regression model to examine diamonds with similar carat, clarity, and color.

Data source and reproducibility

The dataset is ggplot2::diamonds, included in the ggplot2 package. This vignette requires R and the packages dplyr, ggplot2, knitr, and scales. Install them if needed with install.packages(c("dplyr", "ggplot2", "knitr", "scales")). To reproduce the analysis, open this .qmd in RStudio and select Render. No local data files are required.


Extension: Exploring Diamond Quality and Price

Contributed by Zaina Hassan

Introduction

The original vignette explores how diamond prices vary by cut and carat size. However, other characteristics, such as clarity and color, can also influence price. As someone interested in understanding what makes one diamond more expensive than another, I wanted to extend this analysis by comparing diamonds of nearly identical sizes.

This extension focuses on the following question: How do cut, clarity, and color relate to diamond prices when comparing approximately one carat diamonds?

I will demonstrate additional Tidyverse functions, including filter(), pivot_wider(), and slice_min(), along with a heatmap using geom_tile().

1. Filter diamonds by carat weight

The filter() function allows us to select observations that meet specific conditions. Since carat weight plays a major role in diamond pricing, I will narrow the dataset to diamonds between 1.00 and 1.09 carats to make the comparisons more consistent.

library(tidyr)

# Select approximately one-carat diamonds
one_carat <- diamonds_clean |>
  filter(carat >= 1.00, carat < 1.10)

# Compare the number of observations
tibble(
  Dataset = c("Original dataset", "Filtered dataset"),
  Observations = c(nrow(diamonds_clean), nrow(one_carat))
) |>
  kable(caption = "Number of diamonds before and after filtering")
Number of diamonds before and after filtering
Dataset Observations
Original dataset 53940
Filtered dataset 7290

Filtering the dataset reduces differences in diamond size, allowing us to focus more closely on other quality characteristics.

2. Calculate price per carat

Although the selected diamonds are similar in size, their weights are not identical. Using mutate(), we can calculate price per carat by dividing the total price by the diamond’s carat weight.

one_carat <- one_carat |>
  mutate(price_per_carat = price / carat)

# Preview the new variable
one_carat |>
  select(carat, cut, color, clarity, price, price_per_carat) |>
  head(10) |>
  kable(digits = 2, caption = "Diamond prices and price per carat")
Diamond prices and price per carat
carat cut color clarity price price_per_carat
1.01 Premium F I1 2781 2753.47
1.01 Fair E I1 2788 2760.40
1.01 Premium H SI2 2788 2760.40
1.05 Very Good J SI2 2789 2656.19
1.05 Fair J SI2 2789 2656.19
1.00 Premium I SI2 2795 2795.00
1.01 Fair E SI2 2797 2769.31
1.04 Premium G I1 2801 2693.27
1.00 Premium J SI2 2801 2801.00
1.00 Fair G I1 2808 2808.00

Price per carat provides a standardized measure for comparing diamonds of slightly different weights.

3. Compare prices across diamond cuts

Building upon the original vignette, I will calculate the median price per carat for each cut using the filtered dataset.

one_carat_summary <- one_carat |>
  group_by(cut) |>
  summarise(
    diamonds = n(),
    median_price_per_carat = median(price_per_carat),
    .groups = "drop"
  ) |>
  arrange(desc(median_price_per_carat))

one_carat_summary |>
  kable(digits = 2, caption = "Median price per carat by cut")
Median price per carat by cut
cut diamonds median_price_per_carat
Ideal 2057 5333.66
Very Good 1771 5127.36
Premium 2121 4915.84
Good 965 4610.38
Fair 376 4048.69
ggplot(one_carat_summary,
       aes(x = cut, y = median_price_per_carat, fill = cut)) +
  geom_col(width = 0.7) +
  scale_fill_manual(values = c(
    "Fair" = "#EED5E3",
    "Good" = "#DDA9C5",
    "Very Good" = "#C47DAA",
    "Premium" = "#A65B91",
    "Ideal" = "#783D78"
  )) +
  scale_y_continuous(labels = scales::label_dollar()) +
  labs(
    title = "How Does Diamond Cut Relate to Price?",
    subtitle = "Diamonds between 1.00 and 1.09 carats",
    x = "Diamond cut",
    y = "Median price per carat",
  ) +
  theme_minimal() +
  theme(legend.position = "none")

Interpretation: Among diamonds between 1.00 and 1.09 carats, Ideal cut diamonds have the highest median price per carat at approximately $5,300, while Fair cut diamonds have the lowest at approximately $4,050. Interestingly, Very Good diamonds have a slightly higher median price per carat than Premium diamonds. This suggests that better cut quality is generally associated with higher prices, but cut alone does not explain all pricing differences. Other characteristics, such as clarity and color, may contribute to this pattern.

4. Reshape diamond prices with pivot_wider()

The pivot_wider() function from tidyr transforms data from long format into wide format. This is particularly useful when we want to compare multiple categories side by side.

To make our comparison more consistent, I will focus on diamonds with color grade G and calculate the median price per carat for each combination of cut and clarity.

# Keep diamonds within the same color grade
diamond_quality <- one_carat |>
  filter(color == "G") |>
  group_by(cut, clarity) |>
  summarise(
    diamonds = n(),
    median_price_per_carat = median(price_per_carat),
    .groups = "drop"
  )

# Convert clarity categories into individual columns
diamond_wide <- diamond_quality |>
  select(cut, clarity, median_price_per_carat) |>
  pivot_wider(
    names_from = clarity,
    values_from = median_price_per_carat,
    names_sort = TRUE
  )

diamond_wide |>
  kable(digits = 0,
        caption = "Median price per carat by cut and clarity for G-color diamonds")
Median price per carat by cut and clarity for G-color diamonds
cut I1 SI2 SI1 VS2 VS1 VVS2 VVS1 IF
Fair 2331 3427 3965 5242 5635 4928 NA NA
Good 2298 3895 4543 5621 6204 7259 7337 NA
Very Good 2930 4112 4707 5880 6464 7205 7716 7970
Premium 2760 4088 4671 5967 6435 7453 7848 8323
Ideal 3316 4284 4982 6275 6994 7948 8210 8691

Interpretation: Reshaping the data into wide format makes it easier to compare diamond prices across clarity grades. Among G color diamonds with VS2 clarity, the median price per carat ranges from $5,242 for Fair-cut diamonds to $6,275 for Ideal cut diamonds. Missing values indicate that certain combinations of cut and clarity are not represented in the filtered dataset. This demonstrates how pivot_wider() can make multidimensional comparisons more accessible.

5. Visualize diamond quality using a heatmap

A heatmap is useful for displaying relationships between two categorical variables and a numerical value. The geom_tile() function creates individual tiles, while the fill color represents the median price per carat.

ggplot(diamond_quality,
       aes(x = clarity, y = cut, fill = median_price_per_carat)) +
  geom_tile(color = "white", linewidth = 0.8) +
  geom_text(
    aes(label = scales::dollar(median_price_per_carat,
                               accuracy = 1)),
    size = 3
  ) +
  scale_fill_gradient(
    low = "#FCE4EC",
    high = "#B56BA5",
    labels = scales::label_dollar()
  ) +
  labs(
    title = "Diamond Prices Across Cut and Clarity",
    subtitle = "G-color diamonds between 1.00 and 1.09 carats",
    x = "Clarity grade",
    y = "Cut quality",
    fill = "Median price\nper carat",
    caption = "Blank cells indicate unavailable combinations."
  ) +
  theme_minimal() +
  theme(panel.grid = element_blank())

Interpretation: The heatmap reveals a generally positive relationship between clarity and price per carat. For Ideal cut diamonds, the median price per carat increases from $3,316 for I1 clarity to $8,691 for IF clarity, an increase of approximately 162%. This pattern suggests that clarity is an important characteristic associated with diamond pricing, even when color and carat weight are relatively consistent.

However, the relationship is not perfectly consistent across all cut categories. For example, Fair cut diamonds with VVS2 clarity have a lower median price per carat than those with VS1 clarity. Differences in sample sizes or other diamond characteristics may contribute to these exceptions.

6. Identify lower-priced diamonds using slice_min()

The slice_min() function selects observations with the smallest values of a specified variable. In this example, I will use it to identify the diamond with the lowest price per carat within each cut category.

To make the comparison more consistent, I will only consider diamonds with G color and VS2 clarity.

affordable_diamonds <- one_carat |>
  filter(color == "G", clarity == "VS2") |>
  group_by(cut) |>
  slice_min(
    order_by = price_per_carat,
    n = 1,
    with_ties = FALSE
  ) |>
  ungroup() |>
  select(cut, carat, color, clarity, price, price_per_carat) |>
  arrange(price_per_carat)

affordable_diamonds |>
  kable(digits = 2,
        caption = "Lowest price per carat within each available cut category")
Lowest price per carat within each available cut category
cut carat color clarity price price_per_carat
Fair 1.01 G VS2 4072 4031.68
Premium 1.09 G VS2 5098 4677.06
Good 1.00 G VS2 4838 4838.00
Very Good 1.01 G VS2 5119 5068.32
Ideal 1.08 G VS2 5559 5147.22

Interpretation: Among diamonds with G color and VS2 clarity, the Fair cut diamond has the lowest price per carat at $4,031.68. However, the Premium cut diamond stands out as an interesting alternative, costing $4,677.06 per carat compared to $5,147.22 for the lowest priced Ideal cut diamond.

The selected Premium diamond is also slightly larger at 1.09 carats compared to the Ideal diamond at 1.08 carats, while costing $461 less in total. This demonstrates how slice_min() can help identify potentially attractive options based on specific purchasing preferences. However, affordability should not be confused with overall quality, as other diamond characteristics may influence value.

7. Validate the extension

Similar to the original vignette, I will perform a few checks to ensure that the transformations were completed correctly.

# Confirm that all diamonds meet the selected carat range
stopifnot(all(one_carat$carat >= 1.00))
stopifnot(all(one_carat$carat < 1.10))

# Confirm that calculated prices are valid
stopifnot(all(is.finite(one_carat$price_per_carat)))
stopifnot(all(one_carat$price_per_carat > 0))

# Confirm that selected diamonds meet the quality criteria
stopifnot(nrow(affordable_diamonds) > 0)
stopifnot(all(affordable_diamonds$color == "G"))
stopifnot(all(affordable_diamonds$clarity == "VS2"))

cat("All extension checks passed.")
All extension checks passed.

Extension Conclusion

This extension builds upon Chanice’s original diamond price analysis by examining diamonds with more comparable characteristics. By narrowing the carat range, calculating price per carat, and considering clarity and color, I was able to explore pricing differences beyond cut quality alone.

The results showed that Ideal cut diamonds generally have higher median prices per carat and that higher clarity grades are typically associated with higher prices. However, the relationship between quality and price is not always straightforward. For example, a Premium cut diamond with G color and VS2 clarity was slightly larger and $461 less expensive than the selected Ideal cut diamond with the same color and clarity.

Through this extension, I demonstrated how filter(), pivot_wider(), slice_min(), and geom_tile() can be used to transform, compare, and visualize data. What I found particularly interesting was how these functions could be applied to a real-world purchasing decision rather than simply producing summary statistics.

This analysis demonstrates the importance of considering multiple variables when comparing prices. The findings are descriptive rather than causal, and the dataset does not necessarily reflect current retail diamond prices. Differences in group sample sizes and other diamond characteristics should also be considered when interpreting the results.

Additional package and references

This extension also requires the tidyr package.