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

single

bookMapping Variables to Aesthetics

Svep för att visa menyn

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.

Uppgift

Svep för att börja koda

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 desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 2
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt