1. Install and Load ggplot2

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3

Set a working Directory

setwd("~/R training")

Import dataset

gss <-read.csv("GSSsubset.csv")

2. Creating Basic Plot

Example: Scatter plot of ‘income’ vs ‘age’

ggplot(gss, aes(x = age, y = income)) +
  geom_point(color = "blue") +
  labs(title = "Income vs Age", x = "Age", y = "Income") +
  theme_minimal()

Bar Plot***Display the count or summary of categorical data.

———————————————–

Example: Bar plot of ‘gender’ counts

ggplot(gss, aes(x = sex)) +
  geom_bar(fill = "green") +
  labs(title = "Gender Distribution", x = "Gender", y = "Count") +
  theme_classic()

#Histogram***Show the distribution of a single variable. # ———————————————– # Example: Histogram of ‘income’

ggplot(gss, aes(x = income)) +
  geom_histogram(binwidth = 10000, fill = "orange", color = "black") +
  labs(title = "Income Distribution", x = "Income", y = "Frequency") +
  theme_light()

#Boxplot***Summarize the distribution of a continuous variable across categories. # ———————————————– # Example: Boxplot of ‘income’ by ‘gender’

ggplot(gss, aes(x = sex, y = income)) +
  geom_boxplot(fill = "purple") +
  labs(title = "Income by Gender", x = "Gender", y = "Income") +
  theme_bw()

3. Customizing Plots

———————————————–

Adding Titles and Labels***Customize the title, axis labels, and legend.

———————————————–

Example: Scatter plot with customizations

ggplot(gss, aes(x = age, y = income, color = sex)) +
  geom_point(size = 3) +
  labs(title = "Income vs Age by Gender",
       x = "Age (years)",
       y = "Income ($)",
       color = "Gender") +
  theme_minimal()

Changing Themes***Use different themes for better aesthetics.

———————————————–

Example: Scatter plot with a dark theme

ggplot(gss, aes(x = age, y = income)) +
  geom_point(color = "tomato") +
  labs(title = "Income vs Age", 
       x = "Age", 
       y = "Income") +
  theme_classic()

Modifying Colors, Shapes, and Sizes

Enhance visualizations by modifying aesthetics.

———————————————–

Example: Scatter plot with customized colors and sizes

ggplot(gss, aes(x = age, y = income, color = sex, size = income)) +
  geom_point(alpha = 0.6) +
  scale_color_manual(values = c("red", "blue")) +
  labs(title = "Income vs Age by Gender", x = "Age", y = "Income") +
  theme_classic()

View(gss)