Styling Markers in ggplot2
How to Style Markers in ggplot2 with Plotly.
Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Sign up for early access now.
Default point plot
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
ggplotly(p)
Add colour
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point(aes(colour = factor(cyl)))
ggplotly(p)
Changing shapes of data points
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point(aes(shape = factor(cyl)))
ggplotly(p)
Changing size of data points
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point(aes(size = qsec))
ggplotly(p)
Manually setting aesthetics
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point(colour = "red", size = 3)
ggplotly(p)
Optional shape arguments
For shapes that have a border (like shape 21), you can colour the inside and outside separately. Use the stroke aesthetic to modify the width of the border.
library(plotly)
library(ggplot2)
p <-
ggplot(mtcars, aes(wt, mpg)) +
geom_point(shape = 21, colour = "black", fill = "white", size = 5, stroke = 5)
ggplotly(p)
Mix multiples shapes
You can create interesting shapes by layering multiple points of different sizes.
Default plot:
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt, shape = factor(cyl)))
p <-
p +
geom_point(aes(colour = factor(cyl)), size = 4) +
geom_point(colour = "grey90", size = 1.5)
ggplotly(p)
Mixed shapes:
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt, shape = factor(cyl)))
p <-
p +
geom_point(colour = "black", size = 4.5) +
geom_point(colour = "pink", size = 4) +
geom_point(aes(shape = factor(cyl)))
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)