1

I'm trying to get a plot_ly (in R) faceted histogram plot to look like a ggplot2 plot, using facets. I can see this question How to facet a plot_ly() chart?, which allows me to make a faceted histogram plot, but although I can fix the chosen bins, I can't fix the x axis title to be consistent, nor the range of the x axis, nor can I choose different colour for the individual histogram facets.

The following works as a minimal example:

library(plotly)
library(dplyr)

x <- data.frame(Ancestry = as.factor(sample(1:7,200, replace=T)), Est.Age = rnorm(200, mean=50, sd=20))

x %>% group_by(Ancestry) %>%
  group_map (~ plot_ly(data = ., x = ~Est.Age, color = ~Ancestry,
                       type = "histogram", nbinsx = 18, bingroup = 1), .keep = TRUE) %>%
  subplot(nrow=3, shareX=TRUE) %>% layout(xaxis = list(title = "Age"))

This code snippet produces the following plot (or similar, depending on the random number):

enter image description here

What I would like to see is a consistent x-axis across all plots (for comparison purposes), and the same x-axis title ("Age" in this case). I would also like to change the colour of the individual plots in the facets to be consistent with other plots I'm generating on the same dataset, which aren't faceted. How can I do this with plot_ly in R?

EDIT: I should say that I want the facets based on a factor in my dataframe, and I want the colours to be based on a list of colours in the same order as the factors in the dataframe.

user36196
  • 133
  • 11

1 Answers1

1

Here is one possible way using ggplotly:

p <-ggplot(x, aes(x = Est.Age, fill=Ancestry))+
  geom_histogram(bins = 10)+
  facet_wrap(.~Ancestry)

ggplotly(
  p = ggplot2::last_plot()
)

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66