aes in ggplot2

How assign aesthetics in ggplot2 and R.


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.

Fill

library(plotly)

ds <- data.frame(x = 1:10,
                 y = sample(10:30, size = 10),
                 group = LETTERS[1:2])

# Use the fill aesthetic to specify the fill color for the bars
p <- ggplot(ds, aes(x, y)) +
  geom_bar(aes(fill = group), stat = "identity") +
  ggtitle("Filled bar chart")

fig <- ggplotly(p)

fig

Group

library(plotly)

x1 <- 1:100
x2 <- x1 + 100
x3 <- x2 + 100

x <-  c(x1, x2, x3)
y <- c(2*x1, 5*x2, -2*x3)

group <-  c(rep("A", length(x1)),
           rep("B", length(x2)),
           rep("C", length(x3)))

ds <- data.frame(x, y, group)

# Use the group aesthetic to ensure lines are drawn separately for each group
p <- ggplot(ds, aes(x, y)) +
  geom_line(aes(group = group, color = group), size = 2) +
  ggtitle("Group specific line chart")

fig <- ggplotly(p)

fig

Label

library(plotly)

ds <- data.frame(x = rnorm(10),
                 y = rnorm(10),
                 group = LETTERS[1:2])

p <- ggplot(ds, aes(x, y)) +
  geom_point(aes(color = group), size = 7) +
  geom_text(aes(label = group), size = 4) +
  ggtitle("Annotation with labels")

fig <- ggplotly(p)

fig

Shape

library(plotly)

ds <- data.frame(x = letters[1:5],
                 y = rnorm(20),
                 group = LETTERS[1:4])

# Use aes shape to map individual points and or different groups to different shapes
p <- ggplot(ds, aes(x, y)) +
  geom_point(aes(color = group, shape = group), size = 5) +
  geom_line(aes(group = group, linetype = group)) +
  ggtitle("Groupwise shapes and line types")

fig <- ggplotly(p)

fig

Inspired by ggplot2 documentation

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)