Add Line Segment & Curve to ggplot2 Plot in R (Examples) | geom_segment() & geom_curve() Functions

preview_player
Показать описание
R code of this video:

y = c(5, 3, 4, 8, 2, 3))
data # Print example data frame

library("ggplot2") # Load ggplot2 package

ggp <- ggplot(data, aes(x, y)) + # ggplot2 plot without lines & curves
geom_point()
ggp # Draw ggplot2 plot

ggp + # Draw line segment
geom_segment(x = 2.5,
y = 3,
xend = 5,
yend = 7)

ggp + # Modify color, size & linetype
geom_segment(x = 2.5,
y = 3,
xend = 5,
yend = 7,
col = "#1b98e0",
size = 5,
linetype = "dashed")

y = c(4.5, 5, 2),
xend = c(6, 8, 5),
yend = c(7, 5, 6),
col = paste0("line_", letters[1:3]))
data_lines # Print data for multiple segments

ggp + # Draw multiple line segments
geom_segment(data = data_lines,
aes(x = x,
y = y,
xend = xend,
yend = yend,
col = col))

ggp + # Draw curve
geom_curve(x = 2.5,
y = 3,
xend = 5,
yend = 7)

ggp + # Modify curvature, angle & ncp
geom_curve(x = 2.5,
y = 3,
xend = 5,
yend = 7,
curvature = 0.8,
angle = 40,
ncp = 20)

ggp + # Draw line segment & curve
geom_segment(x = 2.5,
y = 3,
xend = 5,
yend = 7,
col = 2) +
geom_curve(x = 2.5,
y = 3,
xend = 5,
yend = 7,
col = 3)

data_facet <- data # Create data with groups & subgroups
data_facet$group = LETTERS[1:3]
data_facet$subgroup = letters[1:2]
data_facet # Print data with groups & subgroups

ggp_facet <- ggplot(data_facet, aes(x, y)) + # Create ggplot2 facet plot
geom_point() +
facet_grid(subgroup ~ group)
ggp_facet # Draw ggplot2 facet plot

y = 3:4,
xend = c(3, 5),
yend = 7:6,
group = c("A", "C"),
subgroup = c("a", "b"),
col = paste0("line_", 1:2))
data_facet_lines # Print data for lines in facets

ggp_facet + # Draw lines in certain facets
geom_segment(data = data_facet_lines,
aes(x = x,
y = y,
xend = xend,
yend = yend,
col = col),

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

Why if i'm trying the col argument i got the Error : Discrete value supplied to continues scale

mazeenourek