0% found this document useful (0 votes)
21 views4 pages

Data Visualization with ggplot2 in R

The document contains four R code exercises that analyze different datasets using ggplot2. Exercise 1 analyzes the mpg dataset and creates boxplots of highway MPG by manufacturer and class. Exercise 2 analyzes diamonds data and creates histograms and bar charts. Exercise 3 performs PCA on iris data and creates scatter plots and a correlation heatmap of the PCs. Exercise 4 transforms variables in the Animals dataset and checks normality before making scatter plots.

Uploaded by

aieditor audio
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views4 pages

Data Visualization with ggplot2 in R

The document contains four R code exercises that analyze different datasets using ggplot2. Exercise 1 analyzes the mpg dataset and creates boxplots of highway MPG by manufacturer and class. Exercise 2 analyzes diamonds data and creates histograms and bar charts. Exercise 3 performs PCA on iris data and creates scatter plots and a correlation heatmap of the PCs. Exercise 4 transforms variables in the Animals dataset and checks normality before making scatter plots.

Uploaded by

aieditor audio
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

```{r}

# Exercise 1

# Load required library


library(ggplot2)

# Load the mpg dataset


data(mpg)

# (a) Plotting hwy mpg against manufacturers


# Calculate median hwy mpg for each manufacturer
manufacturer_median <- tapply(mpg$hwy, mpg$manufacturer, median)
# Order manufacturers based on median hwy mpg
ordered_manufacturers <- names(sort(manufacturer_median, decreasing = TRUE))
# Plotting
ggplot(mpg, aes(x = reorder(manufacturer, -hwy, FUN = median), y = hwy)) +
geom_boxplot() +
coord_flip() +
labs(x = "Manufacturer", y = "Highway MPG") +
theme_minimal() +
theme([Link].y = element_text(size = 8)) +
scale_x_discrete(limits = ordered_manufacturers)

# (b) Plotting hwy mpg against class


# Calculate median hwy mpg for each class
class_median <- tapply(mpg$hwy, mpg$class, median)
# Order classes based on median hwy mpg
ordered_class <- names(sort(class_median, decreasing = TRUE))
# Plotting
ggplot(mpg, aes(x = reorder(class, -hwy, FUN = median), y = hwy)) +
geom_boxplot() +
coord_flip() +
labs(x = "Class", y = "Highway MPG") +
theme_minimal() +
theme([Link].y = element_text(size = 8)) +
scale_x_discrete(limits = ordered_class)

# (c) Bar chart of manufacturers in terms of numbers of different types of cars


manufactured
ggplot(mpg, aes(x = manufacturer)) +
geom_bar() +
labs(x = "Manufacturer", y = "Count") +
theme([Link].x = element_text(angle = 45, hjust = 1)) +
coord_flip()

```

```{r}
# Exercise 2

# Load required library


library(ggplot2)

# Load the diamonds dataset


data(diamonds)

# (a) Histograms for carat and price


ggplot(diamonds, aes(x = carat)) +
geom_histogram(binwidth = 0.1, fill = "blue", color = "black") +
labs(x = "Carat", y = "Frequency") +
theme_minimal()

ggplot(diamonds, aes(x = price)) +


geom_histogram(binwidth = 1000, fill = "green", color = "black") +
labs(x = "Price", y = "Frequency") +
theme_minimal()

# (b) Bar charts of cut proportioned in terms of color


ggplot(diamonds, aes(x = cut, fill = color)) +
geom_bar(position = "fill") +
labs(x = "Cut", y = "Proportion") +
theme_minimal()

# Bar charts of cuts proportioned in terms of clarity


ggplot(diamonds, aes(x = cut, fill = clarity)) +
geom_bar(position = "fill") +
labs(x = "Cut", y = "Proportion") +
theme_minimal()

# (c) Scatter plot of cut, carat, and price


ggplot(diamonds, aes(x = carat, y = price, color = cut)) +
geom_point() +
labs(x = "Carat", y = "Price") +
theme_minimal()

```

```{r}
# Exercise 3

# Load required library


library(ggplot2)

# Load the iris dataset


data(iris)

# (a) Obtain PC scores


# Perform PCA
pca <- prcomp(iris[, -5], scale. = TRUE)
# Extract PC scores
pc_scores <- [Link](pca$x)

# (b) Scatter plot representing PC1 vs. PC2 with data clusters marked
# Combine PC scores with species
pc_scores$Species <- iris$Species
# Plotting
ggplot(pc_scores, aes(x = PC1, y = PC2, color = Species)) +
geom_point() +
labs(x = "PC1", y = "PC2") +
theme_minimal()

# (c) Correlation heatmap between PC scores


correlation_matrix <- cor(pc_scores[, -4])
# Plotting
ggplot(correlation_matrix, aes(x = Var1, y = Var2, fill = value)) +
geom_tile() +
scale_fill_gradient(low = "blue", high = "red") +
labs(x = "PC Scores", y = "PC Scores", fill = "Correlation") +
theme_minimal() +
theme([Link].x = element_text(angle = 45, hjust = 1))

```

```{r}
# Exercise 4

# Load required libraries


library(ggplot2)
library(e1071)

# Load the Animals dataset


data(Animals)

# Task 1: Check normality of variables


# Histogram and Q-Q plot for brain weight
ggplot(Animals, aes(x = brain)) +
geom_histogram(fill = "blue", color = "black") +
labs(x = "Brain Weight (g)", y = "Frequency") +
theme_minimal()

qqnorm(Animals$brain)
qqline(Animals$brain)

# Histogram and Q-Q plot for body weight


ggplot(Animals, aes(x = body)) +
geom_histogram(fill = "green", color = "black") +
labs(x = "Body Weight (kg)", y = "Frequency") +
theme_minimal()

qqnorm(Animals$body)
qqline(Animals$body)

# Task 2: Find lambda values for power transformation


# Box-Cox transformation for brain weight
lambda_brain <- boxcox(Animals$brain)$lambda
# Box-Cox transformation for body weight
lambda_body <- boxcox(Animals$body)$lambda

# Task 3: Apply power transformation and check normality


# Power transformation for brain weight
transformed_brain <- Animals$brain^lambda_brain
# Histogram and Q-Q plot for transformed brain weight
ggplot([Link](transformed_brain), aes(x = transformed_brain)) +
geom_histogram(fill = "blue", color = "black") +
labs(x = "Transformed Brain Weight", y = "Frequency") +
theme_minimal()

qqnorm(transformed_brain)
qqline(transformed_brain)

# Power transformation for body weight


transformed_body <- Animals$body^lambda_body
# Histogram and Q-Q plot for transformed body weight
ggplot([Link](transformed_body), aes(x = transformed_body)) +
geom_histogram(fill = "green", color = "black") +
labs(x = "Transformed Body Weight", y = "Frequency") +
theme_minimal()
qqnorm(transformed_body)
qqline(transformed_body)

# Task 4: Create scatter plot of transformed data


ggplot([Link](brain = transformed_brain, body = transformed_body), aes(x =
brain, y = body)) +
geom_point() +
labs(x = "Transformed Brain Weight", y = "Transformed Body Weight") +
theme_minimal()

```

Common questions

Powered by AI

The Box-Cox transformation is applied to stabilize variance and make the data more normally distributed. For the Animal dataset, the brain and body weights exhibited non-normal distribution, which could skew analyses. By finding appropriate lambda values and applying the transformation, distributions of brain and body weights become more symmetric and closer to normality, as evidenced by the improved appearance of histograms and Q-Q plots after transformation .

Clustering in PCA visualization helps identify natural groupings within data. In the iris dataset, PCA reduces features to PC1 and PC2 where plotting these components visually separates iris species by their PC scores. This clustering visualization aids in understanding how species are related and differentiated based on measured attributes, highlighting variance captured by the principal components .

Multi-variable scatter plots allow for a detailed exploration of relationships between multiple variables, providing insights not apparent from univariate analyses. In the diamonds dataset, using cut as a color-coded factor in the scatter plot of carat versus price reveals price variation trends across different cuts, aiding in visual correlation analysis between these three factors. This format facilitates the identification of patterns and outliers, supporting decision-making in market analysis .

Histograms for carat and price provide an overview of the distribution patterns, revealing skewness, multi-modality, or dispersion. In the diamonds dataset, the carat histogram shows right-skewness, indicating more diamonds with lower carat values. The price histogram also exhibits right-skewness with most diamonds at lower prices. These patterns help to understand market dynamics, inventory considerations, and price ranges .

PCA, being a technique that relies on covariance and numeric computations, is inherently non-suited for categorical variables. In the iris dataset, PCA is applied to numerical attributes only, excluding the species (categorical variable), as including it directly would misrepresent variance. Solutions involve first converting categorical variables using techniques like one-hot encoding, ensuring comprehensive data transformation without skewing principal component computations .

PCA reduces the dimensionality of datasets by transforming to a new set of variables (principal components) that summarize the original data with minimal loss of information. In the iris dataset, PCA reduces the four original features to two principal components, PC1 and PC2, capturing significant variance. This allows for effective visualization of the data in two dimensions, where species groups can be distinguished based on variance patterns, enhancing interpretability and revealing intrinsic structure .

Bar charts effectively display frequency or proportion distributions of categorical data, facilitating an understanding of qualitative attributes. In the diamonds dataset, bar charts show cut proportions in terms of color, enabling visual comparison of how different quality grades vary across color categories. This visual approach highlights grading biases or market trends in categorical dimensions, crucial for inventory management and consumer insights .

Ordering categories by median values in ggplot2 visualizations ensures a coherent representation of data positioning, enhancing interpretability. For example, in the mpg dataset, manufacturers and vehicle classes are ordered by median hwy mpg to emphasize relative performance differences. This ordered approach makes it easier to visually compare and assess categories based on central tendencies rather than arbitrary or alphabetical orderings .

The coord_flip() function in ggplot2 enhances categorical data visualization by inverting the axes, effectively switching from a vertical to a horizontal layout. This approach is particularly useful for handling categorical variables with long labels, improving readability. In the mpg dataset, flipping the coordinates makes it easier to read and compare category labels such as manufacturers or vehicle classes, especially when presenting ordered box plots for hwy mpg .

By comparing the median hwy mpg across manufacturers, we can identify which manufacturers produce vehicles that generally have higher or lower fuel efficiency on highways. Using median values provides a more robust measure that is less sensitive to outliers compared to mean values. This helps in understanding which manufacturers focus on fuel efficiency and can guide consumer decisions or policy assessments regarding environmental impacts .

You might also like