Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ggplot lines run to the edge?

I have data (depth over time) that I want to display with a line plot. For clarity, I want to zoom in on a section but still show the user that the data continues outside the bounds of the plot. So I want the lines to stop at the plot's edge, rather than at the last point. This is straightforward enough in base graphics but I can't make it work in ggplot. Here's an example with base:

d <- data.frame(x = 1:10, y = 1:10)
plot(d$x, d$y, xlim = c(2,9))
lines(d$x, d$y)

line plot in base graphics

A similar approach with ggplot doesn't work; the lines stop at the last point. Example:

d <- data.frame(x = 1:10, y = 1:10)
ggplot(d, aes(x, y)) + geom_point() + geom_line() + xlim(2,9)

line plot in ggplot

Is there a way to get lines to run to the plot's edge in ggplot? Thanks.

like image 669
Corned Beef Hash Map Avatar asked Jun 10 '16 17:06

Corned Beef Hash Map


People also ask

What does %>% do in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Introducing magrittr. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

How do you add a smooth fit line in R?

We can plot a smooth line using the “loess” method of the geom_smooth() function. The only difference, in this case, is that we have passed method=loess, unlike lm in the previous case. Here, “loess” stands for “local regression fitting“. This method plots a smooth local regression line.

How do you add a smooth line to a scatter plot in R?

A scatter plot can be created using the function plot(x, y). The function lm() will be used to fit linear models between y and x. A regression line will be added on the plot using the function abline(), which takes the output of lm() as an argument. You can also add a smoothing line using the function loess().

What is Geom_line in ggplot?

geom_line() connects them in order of the variable on the x axis. geom_step() creates a stairstep plot, highlighting exactly when changes occur. The group aesthetic determines which cases are connected together.


1 Answers

try this

d <- data.frame(x = 1:10, y = 1:10)
ggplot(d, aes(x, y)) + geom_point() + geom_line() + coord_cartesian(xlim = c(0,9))

enter image description here

like image 135
Tomas H Avatar answered Sep 29 '22 08:09

Tomas H