1

I am trying to convert a ggplot polar chart to a plotly one. I am missing the cumulative of geom_area in plotly and the filled color for each trace that is not going to the origin for both trace. The goal is to be as closed as possible to the ggplot view.

df <- data.frame(angle = rep(seq(0, 360, 45), 4), frequency = rep(1:9, 4), z = as.character(c(rep(1, 9), rep(2, 9))))
df <- aggregate(frequency ~ angle + z, data = df, sum)

pl <- ggplot(df,aes(x=angle,y=frequency,fill=z)) + geom_area() + coord_polar() + scale_x_continuous(breaks=angle, labels=c("N", "NE", "E", "SE", "S", "SO", "O", "NO", "N"))
pl

ggplot one

p <- plot_ly(type = 'scatterpolar', mode = "scatter")
for (g in 1:2){
  p <- p %>%
    add_trace(data = df[df$z == g,],
              theta = ~df$angle, r = ~df$frequency,
              opacity = 1, fill = "tozeroy")
}
p <- p %>% layout(
  polar = list(radialaxis = list(angle = 90),
               angularaxis = list(
                 rotation = 90,
                 direction = 'clockwise',
                 ticktext =  c("N", "NE", "E", "SE", "S", "SO", "O", "NO", "N"),
                 tickvals = seq(0, 360, 45)
               )
  )
)
p

plotly one

Thank you for any clue on how to do this.

Clemsang
  • 5,053
  • 3
  • 23
  • 41

1 Answers1

2

Here is a starting point for the solution of your problem:

k <- 100
df <- data.frame(angle = rep(seq(0, 360, length.out=k), 4), 
                 frequency = rep(1:k, 4), 
                 z = as.character(c(rep(1, k), rep(2, k))))
df <- aggregate(frequency ~ angle + z, data = df, sum)   
df$frequency[df$z==2] <- df$frequency[df$z==2]/2

p <- plot_ly(data=df, type = 'scatterpolar', mode = "lines") %>%
     add_trace(theta=~angle,r=~frequency,fill="toself", color=~z)
p <- p %>% layout(
  polar = list(radialaxis = list(angle = 90),
               angularaxis = list(
                 rotation = 90,
                 direction = 'clockwise',
                 ticktext =  c("N", "NE", "E", "SE", "S", "SO", "O", "NO", "N"),
                 tickvals = seq(0, 360, 45)
               )
  )
)
p

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58
  • Thank you very much for your time. Indeed the smoothing of the plot is missing, you got it by modifying the initial data frame that I can't do – Clemsang Apr 26 '19 at 16:24