1

I'm using plotly in R, though I don't think it should matter. Basically, I want to draw a line plot of a set of points that don't correspond to a function (in the mathematical sense). See the below code for a simple example, I think it's fairly obvious what the problem is. I want the second plot to simply look like the first one inverted across the x/y axes.

To clarify, the example below could be solved be using the inverse function (square root), but I'm looking for a generic solution that doesn't rely on having an explicitly invertible function.

library(plotly)
library(magrittr)

x <- seq(from=-2, to=2, length.out = 200)
y <- x^2

p1 <- plot_ly() %>%
  add_lines(x=x, y=y)

p2 <- plot_ly() %>%
  add_lines(x=y, y=x)

enter image description here

enter image description here

1 Answer 1

1

I really think this would depend completely on the specifics of your dataset. In your data sample, you've got a unique x-value for each y. The reason your second figure fails (in the sense that you're not getting a smooth continuous line), is that you no longer have a unique value on your x-axis for each value on your y-axis. To get the visual result you seem to be looking for with this particular dataset, you could separate positive and negative numbers for your y axis and apply two traces:

enter image description here

Complete code:

library(plotly)
library(magrittr)


x <- seq(from=-2, to=2, length.out = 200)
y <- x^2

df1 = data.frame(x1=x,
                y1=y
                )

df2 <- filter(df1, x1 <= 0)
df3 <- filter(df1, x1  > 0)


p1 <- plot_ly() %>%
  add_lines(data=df2, x=~y1 , y=~x1, line = list(color = '#636EFA', width = 1.5))

p1 <- p1 %>% add_lines(data=df3, x=~y1 , y=~x1, line = list(color = '#636EFA', width = 1.5))

p1
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I ended up doing for the case I was trying to work with, though my concern is that it doesn't generalize very cleanly. For an arbitrary set of data you'd need to split it along some y-value, identify each different branch, and separate them. It's remarkable to me that there doesn't seem to be an easier way within plotly, especially given the ease of--for example--making a histogram on the y-axis instead of the x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.