Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Mapping Variables to Aesthetics | section
Hands-On Data Visualization with ggplot2 in R
Sektion 1. Kapitel 2
single

single

bookMapping Variables to Aesthetics

Stryg for at vise menuen

When using ggplot2 in R, aesthetic mappings are the way you connect your data variables to visual properties of your plot. These properties, called aesthetics, include features like position on the x- and y-axes, color, size, shape, and more. By mapping variables to these aesthetics, you make your data visually meaningful: for example, mapping a variable to color can help you distinguish groups, while mapping to size can show magnitude. Aesthetic mappings are set inside the aes() function, either globally in ggplot() or locally within a specific geom layer. This approach allows you to quickly explore relationships and patterns in your data, making your plots both informative and visually appealing.

12345678910111213
library(ggplot2) # Sample data df <- data.frame( height = c(150, 160, 170, 180, 190), weight = c(55, 65, 72, 80, 90), gender = c("Female", "Male", "Female", "Male", "Male"), age = c(23, 35, 29, 41, 33) ) # Scatter plot mapping variables to aesthetics ggplot(df, aes(x = height, y = weight, color = gender, size = age)) + geom_point()
copy

Changing which variables are mapped to which aesthetics can dramatically alter both the appearance of your plot and the insights you can draw from it. For instance, mapping gender to color allows you to easily compare groups, while mapping age to size adds an extra dimension, showing how another variable relates to the others. If you swap these mappings - say, mapping age to color and gender to size - the visual emphasis and the story your plot tells will change. Thoughtful aesthetic mapping helps you highlight patterns, identify outliers, and communicate your findings more effectively.

Opgave

Swipe to start coding

Use the provided data data frame to create a scatter plot with ggplot2.

  • Map hours_studied to the x-axis.
  • Map exam_score to the y-axis.
  • Map student_group to the color aesthetic.
  • Map assignments_completed to the size aesthetic.
  • Add a point layer to display the data.

Løsning

Switch to desktopSkift til skrivebord for at øve i den virkelige verdenFortsæt der, hvor du er, med en af nedenstående muligheder
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 2
single

single

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

some-alt