plotly in R : setting ranges on axis with "reversed" autorange - r

I have a plotly graph in R with a reversed x-axis. I want to be able to play with its ranges. I know it is normal because by design, setting "range" turns "autorange" to "FALSE". https://plot.ly/r/reference/#layout-xaxis-range
But I still need to play with ranges of this reversed axes. Any workarounds, anyone?
Greetings
library(plotly)
s <- seq(1, 8)
plot_ly(x = s, y = s) %>%
add_trace(y = rev(s)) %>%
layout(
xaxis = list(range = c(3,5), autorange="reversed"),
yaxis = list(range = c(2, 5)))

Just retyping my comment above. Using plotly_3.4.3 (development version) and ggplot2_2.1.0. Remove autorange="reversed" from your code and try:
s <- seq(1, 8)
plot_ly(x = s, y = s) %>%
add_trace(y = rev(s)) %>%
layout( xaxis = list(range = c(5,3)), yaxis = list(range = c(2, 5)))

Related

Plotly 3d scatterplot with more than 6 groups

I try to plot a 3d scatterplot with plotly in R with overall 12 groups and cannot find out how to use 12 different symbols and colours.
palette <- distinctColorPalette(12)
pie(rep(1, 12), col=palette)
library(plotly)
fig <- plot_ly(data, x = ~Length..mm., y = ~Width..mm., z = ~Height..mm.,
color = ~spec, colors = palette, symbol =~spec, symbols = ~spec)
fig <- fig %>% layout(scene = list(xaxis = list(title = 'Seed length (mm)'),
yaxis = list(title = 'Seed width (mm)'),
zaxis = list(title = 'Seed heigth (mm)'))
I really appreciate any help you can provide.
this is the output

Anyway to remove the 0 on the y-axis in Plotly R graph?

I have this simple graphic I am making with plotly.
library(plotly)
fig <- plot_ly(x = ~rnorm(50), type = "histogram")
fig
This is the output.
But my goal is this - no 0 on the y-axis.
This could be achieved by setting the tickvals and ticktext manually via layout options. Note that you have to se tickmode="array". One drawback is that this adds some additional space on the left and the top so that you have to additionally set the margins manually.
library(plotly)
set.seed(42)
x <- rnorm(50)
fig <- plot_ly(x = ~x, type = "histogram")
fig %>%
layout(yaxis = list(
tickvals = as.list(seq(0, 20, 2)),
ticktext = as.list(c("", seq(2, 20, 2))),
tickmode = "array"
), margin = list(l = 2, t = 2))

how to change order of R plotly hover labels with "x unified" mode

I'm looking to see if there's a way to change the order of the hoverlabels when using hovermode = "x unified" in the newest version of the R package of plotly (4.9.3). Alternatively, is it possible to revert back to the way the old version of plotly displayed the hoverlabels while still using the current version of the plotly package? From a data visualization perspective, the old way is much clearer in my opinion.
I've included a minimum reproducible example below. When I run this using plotly v4.9.2.1, I get the result shown in Figure A and when I run it in plotly v4.9.3, I get the result shown in Figure B. The benefits to Figure A over Figure B are:
Figure A labels are in descending order relative to the data on each line at the time specified. Also this is reactive to the time period, so if one line moves above another at a different time period, the relative positioning of the label also moves to reflect the ordering of the data. You can see in Figure B that the dark green (y1) line has the lowest value (66) yet it is shown at the top of the hoverlabel box. In figure B, the y1 label is at the bottom.
Figure A labels are attached to the individual lines, so its easier to see the hovertext as it applies to the line in question
Figure A:
Figure B:
Code:
library(plotly)
library(tidyr)
df <- data.frame(Date = seq(as.Date("2018-01-01"),
as.Date("2021-01-01"),
by = "months"),
stringsAsFactors = F)
df$y1 <- seq(0, 100, length.out = nrow(df))
df$y2 <- seq(0, 600, length.out = nrow(df))
df$y3 <- seq(0, 300, length.out = nrow(df))
df$y4 <- seq(0, 200, length.out = nrow(df))
df <- df %>%
pivot_longer(cols = -Date,
names_to = "yname",
values_to = ) %>%
arrange(yname, Date)
mycols <- c("#006633", "#70AD47", "#1F4E78", "#2F75B5", "#C65911", "#EF8C4F",
"#C00000", "#FF8B8B", "#7030A0", "#9966FF")
mycols <- mycols[1:length(unique(df$yname))]
p <- plot_ly()
p <- p %>%
add_trace(data = df,
x = ~Date,
y = ~value,
text = ~yname,
hovertemplate = paste('<b>%{text}</b>',
'<br>%{x}',
'<br>%{y}',
'<extra></extra>'),
color = ~yname, colors = mycols,
name = ~yname, yaxis = "y",
type = "scatter", mode = "lines",
showlegend = T)
p <- p %>%
layout(hovermode = "x unified",
legend = list(x = 1.12, y = .5, xanchor = "left"),
yaxis = list(fixedrange = T),
xaxis = list(title = "",
fixedrange = T,
hoverformat = "%b %d, %Y"),
showlegend = T)
p
Two answers:
the ordering of traces in the unified hoverlabel is always the same, regardless of the relative Y values of the traces. The order is the same as in the legend, so it will follow the ordering of the colors.
You can revert to the previous behavior with hovermode = "x" rather than hovermode = "x unified"

Plotly zerolines at different levels on double axis plot

I'm trying to overlay a line chart and bar chart in plotly (with a vertical line designating an important date) and I'm encountering this issue where the two zero lines are offset instead of on the same line. I've tried messing around with the overlaying = 'y' option within layout and tried changing the order of the three trace components but nothing seems to help. Any ideas how to fix? Below is my code with dummy data:
(Also, bonus points if you can fix my legend-overlapping-y2axis issue)
date <- seq(as.Date("2015/6/1"), by = "month", length.out = 19)
wires_mnth <- c(rep(0,8),100000,750000,1200000,2500000,3100000,5500000,7500000,8000000,9900000,11300000,11000000)
wires_cnt <- c(rep(0,8),100,200,250,325,475,600,750,800,1000,1150,1200)
data <- data.frame(date, wires_mnth)
plot_ly(data) %>%
add_trace(x = ~date, y = ~wires_cnt, type = 'bar', name = 'Wires Count',
yaxis = 'y2', opacity = .5) %>%
add_trace(x = ~date, y = ~wires_mnth, type = 'scatter', mode = 'lines', name
= 'Monthly Wires') %>%
add_trace(x = c(2016,2016), y = c(0, 12000000), type = 'scatter', mode =
"lines", name = 'Sanctions Removed') %>%
layout(title = 'Monthly Aggregate Wire Transfers to Iran',
xaxis = list(title = ''),
yaxis = list(side = 'left', title = 'Wire Amounts (USD)', showgrid =
FALSE, zeroline = FALSE),
yaxis2 = list(side = 'right', overlaying = 'y', title = 'Wires Count',
showgrid = FALSE, zeroline = FALSE)
)
You could add rangemode='nonnegative' to your layout or specify the range manually via range=list(0, max(wires_mnth).
For your bonus question, you can set the x-position of the legend, e.g.
legend = list(x = 1.2)

Multiple Y-axis on graph not aligned

I created a graph through R's Plotly library.
The graph has 2 y-axis's and everything looks fine, except that the y-axis's are misaligned.
How do I "realign" it?
Python answer here
Had the same issue, add rangemode = "tozero" to your overlaying axis
plot_ly(data = dat,
x = x,
y = y,
type = "bar",
name = "Y") %>%
add_trace(data = par,
x = x,
y = Z,
name = "Z",
yaxis = "y2") %>%
layout(yaxis2 = list(overlaying = "y",
side = "right",
rangemode = "tozero"))
In the layout function, you can set axis ranges manually. You can use this to align them. Often, the scale of your two traces will be very different, though.
plot_ly(...) %>%
add_trace(..., yaxis = "y2") %>%
layout(
yaxis = list(
range = c(-2, 2)
),
yaxis2 = list(
range = c(-2, 2)
)
)
You can actually align primary and secondary y axes at any value (not just at 0) and for any plotting function by calculating new y axis limits. Here's a link to some code for a function that can handle any scenario: https://github.com/davidblakneymoore/A-Function-for-Aligning-Values-on-Primary-and-Secondary-Y-Axes-on-Plots-in-R.
This answer in python took JohnCoene's answer one step further:
https://community.plotly.com/t/align-multiple-y-axis-to-one-value-in-plotly/44500/2
The parameters scaleratio can be seen in further detail in the Plotly manual.
By constraining the left and right y-axes to one another you can adjust the scale at which they increase.
plot_ly(data = dat,
x = x,
y = y,
type = "bar",
name = "Y") %>%
add_trace(data = par,
x = x,
y = Z,
name = "Z",
yaxis = "y2") %>%
layout(yaxis = list(scaleanchor = 'y2',
scaleratio = 1, # Or perhaps 0.5 or 2, dep on your figure
constraintoward = 'bottom',
rangemode = "tozero"),
yaxis2 = list(scaleanchor = 'y',
scaleratio = 1, # Or perhaps 0.5 or 2, dep on your figure
overlaying = "y",
constraintoward = 'bottom'
side = "right",
rangemode = "tozero"))

Resources