2
votes

I am currently using a facet_wrap to knit data (html) to an Rmarkdown document. I am looking to use facet_wrap and ggplot to show this data.

This is how the data looks just in ggplot (not plotly):

enter image description here

However, when I use plotly the titles of each plot intersect with the y-axis making interpretability difficult enter image description here

Here is the code to the first plot not using plotly

plot <-  ggplot(dataframe, aes(x = week, y = measure))+
  geom_line(size = 1.25, aes(color = "orange"))+
  geom_point(size = 1.50)+
  theme_economist()+
  geom_smooth(method = 'auto', se = FALSE, size = .50)+
  scale_x_continuous(breaks=seq(0,13,1))+
  scale_y_continuous(labels = scales::dollar_format(scale = .0001, suffix = "K"))+
  facet_wrap(vars(category), scales = "free", ncol = 3, nrow = 6)+
  theme(legend.position = "none")+
  ggtitle('Title')+
    theme(
    panel.grid.major = element_line(linetype = "dotted"),
    axis.title.x = element_text( size = 10, margin=margin(30,0,0,0)),
    axis.title.y = element_text( size = 10, margin=margin(0,30,0,0)),
    axis.text = element_text( size = 10),
    plot.title = element_text( size = 14, margin=margin(0,0,35,0), hjust = 0.5),
    panel.background = element_rect(fill = NA),
    strip.text = element_text(size=10)
  )

Then here is what I do to conver it to plotly

ggplotly(plot)
1

1 Answers

2
votes

Some random data:

require(stats)
r <- function(x) {abs(as.numeric(arima.sim(n=x, list(order=c(1,0,0),ar=0.95)))+10)}
dataframe = data.frame(week = rep(1:13,6), measure = r(13*6), category = rep(as.character(1:6),each=13))

Although I was not able to reproduce the overlapping y-axis labels, you can set the margins between the faceted plots by setting panel.margin.y and panel.margin.x inside the theme():

plot <- ggplot(dataframe, aes(x = week, y = measure))+
  geom_line(size = 1.25, aes(color = "orange"))+
  geom_point(size = 1.50)+
  theme_economist() + 
  geom_smooth(method = 'auto', se = FALSE, size = .50)+
  scale_x_continuous(breaks=seq(0,13,1))+
  scale_y_continuous(labels = scales::dollar_format(scale = .0001, suffix = "K"))+
  facet_wrap(vars(category), scales = "free", ncol = 3, nrow = 6)+
  theme(legend.position = "none")+
  ggtitle('Title')+
    theme(
    panel.grid.major = element_line(linetype = "dotted"),
    axis.title.x = element_text( size = 10, margin=margin(30,0,0,0)),
    axis.title.y = element_text( size = 10, margin=margin(0,30,0,0)),
    axis.text = element_text( size = 10),
    plot.title = element_text( size = 14, margin=margin(0,0,35,0), hjust = 0.5),
    panel.background = element_rect(fill = NA),
    strip.text = element_text(size=10), panel.margin.x = unit(1,"lines"), panel.margin.y = unit(0,"lines")
  )
ggplotly(plot)

You can fine tune the margins to suit your plot.

Before:

> ggplotly(plot)

enter image description here

After:

> ggplotly(plot)

enter image description here