Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple y-axes chart with Plotly in R

Tags:

r

plotly

In Plotly for Python, we have this beautiful multiple y-axis example: enter image description here here is the link for the code.

I tried to do the same with Plotly in R using this code:

  library(plotly)

x <- 1:4
y1 <- c(1,2,3,4)
y2 <- c(4,3,2,1)
y3 <- c(1,4,1,4)
y4 <- c(4,1,4,1)

test <- data.frame(x, y1, y2, y3, y4)

plot_ly(data = test, x = ~x, y = ~y1
        ,type = "scatter", mode = "lines", width = 800, color = I("red")
        ,name = "name01") %>%
  add_trace(x = ~x, y = ~y2, yaxis = "y2", color = I("blue"), name = "name02") %>%
  add_trace(x = ~x, y = ~y3, yaxis = "y3", color = I("purple"), name = "name03") %>%
  add_trace(x = ~x, y = ~y4, yaxis = "y4", color = I("green"), name = "name04") %>%
  layout(
    yaxis = list(
      showline = FALSE, side = "left"
      ,title = "Label 1"
      ,color = "red"
    )
    ,yaxis2 = list(
      showline = FALSE
      ,overlaying = "y"
      ,title = "Label 2", anchor = "free"
      ,color = "blue"
    )
    ,yaxis3 = list(
      showline = FALSE, side = "right", overlaying = "y"
      ,title = "Label 3"
      ,color = "purple"
    )
    ,yaxis4 = list(
      showline = FALSE, side = "right", overlaying = "y", position = 1
      ,title = "Label 4", anchor = "free"
      ,color = "green"
    )
    ,xaxis = list(
      showline = FALSE, zeroline = FALSE, dtick = 1, title = ""
    )
    ,showlegend = FALSE
    ,margin = list(
      pad = 30, b = 90, l = 150, r = 90
    )
    ,legend = list(orientation = "h")
  )

But I get these overlapping labels:

enter image description here

How can I fix it to get a non overlapping chart?

like image 858
Murta Avatar asked Dec 20 '16 18:12

Murta


People also ask

How do you plot two Y axis in plotly?

Multiple Y Axes and Plotly Express Note: At this time, Plotly Express does not support multiple Y axes on a single figure. To make such a figure, use the make_subplots() function in conjunction with graph objects as documented below.

How do I add a secondary axis in plotly?

First, import the necessary functions from the Plotly package and create the secondary axes using the specs parameter in the make_subplots() function as shown. Plot a scatter plot with multiple y-axes. Make the chart readable by adding titles to the x and y axes.

How do you plot multiple Y axis in Python?

Using subplots() method, create a figure and a set of subplots. Plot [1, 2, 3, 4, 5] data points on the left Y-axis scales. Using twinx() method, create a twin of Axes with a shared X-axis but independent Y-axis, ax2. Plot [11, 12, 31, 41, 15] data points on the right Y-axis scale, with blue color.


1 Answers

Try tuning the padding (pad) value for margin argument of layout().

Best I found for your other parameters is with pad = 49

enter image description here

like image 78
HubertL Avatar answered Oct 02 '22 13:10

HubertL