Horizontal and Vertical Lines in ggplot2
How to add Horizontal and Vertical Lines in ggplot2 with Plotly.
New to Plotly?
Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.
Add horizontal line
To do this, use geom_vline()
:
library(plotly)
library(ggplot2)
p <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
geom_vline(xintercept = 3)
ggplotly(p)
Add vertical line
To do this, use geom_hline()
:
library(plotly)
library(ggplot2)
p <- ggplot(data=mtcars, aes(x=wt, y=mpg)) +
geom_point() +
geom_hline(yintercept=20)
ggplotly(p)
Change line type
library(plotly)
library(ggplot2)
p <- ggplot(data=mtcars, aes(x=wt, y=mpg)) +
geom_point() +
geom_vline(xintercept = 3, linetype="dotted",
color = "blue", size=1.5)
ggplotly(p)
library(plotly)
library(ggplot2)
p <- ggplot(data=mtcars, aes(x=wt, y=mpg)) +
geom_point() +
geom_hline(yintercept=20, linetype="dashed",
color = "green", size=4)
ggplotly(p)
Add a segment line
If you do not wish to add line that goes across the whole plot, use geom_segment()
:
library(plotly)
library(ggplot2)
p <- ggplot(data=mtcars, aes(x=wt, y=mpg)) +
geom_point() +
geom_segment(aes(x = 4, y = 15, xend = 4, yend = 27))
ggplotly(p)
Adding regression line
library(plotly)
library(ggplot2)
require(stats)
reg <- lm(mpg ~ wt, data = mtcars)
coeff = coefficients(reg)
eq = paste0("y = ", round(coeff[2],1), "*x + ", round(coeff[1],1))
p <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
geom_abline(intercept = 37, slope = -5, color="red",
linetype="dashed", size=1.5)+
ggtitle(eq)
ggplotly(p)
What About Dash?
Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Learn about how to install Dash for R at https://dashr.plot.ly/installation.
Everywhere in this page that you see fig
, you can display the same figure in a Dash for R application by passing it to the figure
argument of the Graph
component from the built-in dashCoreComponents
package like this:
library(plotly)
fig <- plot_ly()
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... )
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
app <- Dash$new()
app$layout(
htmlDiv(
list(
dccGraph(figure=fig)
)
)
)
app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)