ggplot2 geom_segment() in R: Draw Line Segments
The geom_segment() function in ggplot2 draws line segments between explicit start and end points, specified via x, y, xend, and yend aesthetics. Useful for arrows, lollipop charts, and custom annotations.
ggplot(df, aes(x, y, xend = xend, yend = yend)) + geom_segment() geom_segment(arrow = arrow()) ggplot(df, aes(x, y)) + geom_segment(aes(xend = x, yend = 0)) # lollipop geom_curve(...) # curved version
Need explanation? Read on for examples and pitfalls.
What geom_segment() does in one sentence
geom_segment() draws straight line segments from (x, y) to (xend, yend) for each row of data. Each row produces ONE segment.
Syntax
geom_segment(mapping = NULL, data = NULL, arrow = NULL, lineend = "butt", ...). Requires aes(x, y, xend, yend).
Five common patterns
1. Lollipop chart
2. Arrow segment
3. Connect two points
4. Highlight reference lines
5. Network-like edges
geom_segment requires FOUR aesthetics: x, y, xend, yend. Each row draws ONE segment from (x, y) to (xend, yend).geom_segment() vs geom_curve() vs geom_line()
| Function | Path | Best for |
|---|---|---|
geom_segment() |
Straight line | Explicit endpoints |
geom_curve() |
Curved line | Arc connections |
geom_line() |
Connected points (sorted x) | Trends |
geom_path() |
Connected points (row order) | Trajectories |
A practical workflow
Lollipop charts are a common alternative to bar charts and use geom_segment + geom_point.
Common pitfalls
Pitfall 1: forgetting xend or yend. geom_segment requires all four aesthetics. Missing one errors.
Pitfall 2: arrow direction. arrow appears at the END (xend, yend) by default. Reverse aesthetics if direction is wrong.
geom_segment() does NOT close shapes. It draws ONE segment per row. For closed shapes, use geom_polygon.Try it yourself
Try it: Make a lollipop chart of top 5 mtcars by mpg. Save to ex_plot.
Click to reveal solution
Explanation: Sort by mpg desc, take top 5, draw segment from 0 to mpg with point at the end.
Related ggplot2 functions
After mastering geom_segment, look at:
geom_curve(): curved segmentsarrow(): arrowhead specificationgeom_path()/geom_line(): connected pointsgeom_vline()/geom_hline(): full-axis reference linesannotate(): one-off annotations
FAQ
What does geom_segment do in ggplot2?
geom_segment() draws straight line segments from (x, y) to (xend, yend) for each row of data.
How do I add an arrow to geom_segment?
Pass arrow = arrow(length = unit(0.3, "cm")): geom_segment(arrow = arrow()). Arrow appears at (xend, yend).
What is the difference between geom_segment and geom_line?
geom_segment draws independent segments per row using xend/yend. geom_line connects points across rows with sorted x.
How do I make a lollipop chart?
Combine geom_segment (stick from baseline to value) with geom_point (candy at value).
What is the difference between geom_segment and geom_curve?
geom_segment is straight; geom_curve is curved. Same aesthetics; different visual.