I have data similar to the below, where I'm defining my x-axis categoryorder & categoryarray so that instead of my x-axis being ordered alphabetically (see: a), it's being ordered as specified (see: b).
a <- plot_ly(
x = c("giraffes", "orangutans", "monkeys"),
y = c(20, 14, 23),
name = "SF Zoo",
type = "bar") %>%
layout(xaxis = list(title = "x"),
yaxis = list(title = "y"))
xform <- list(categoryorder = "array",
categoryarray = c("giraffes",
"orangutans",
"monkeys"))
b <- plot_ly(
x = c("giraffes", "orangutans", "monkeys"),
y = c(20, 14, 23),
name = "SF Zoo",
type = "bar") %>%
layout(xaxis = xform,
yaxis = list(title = "y"))
My problem is that once I write "xaxis = xform" in the layout(), I am unable to specify any additional aesthetics for the x-axis without the order reverting to that in (a). for example, I cannot add an x-axis title or change the font size of x-axis labels.
I've tried to spam numerous combinations, i.e., trying this results in no x-axis title:
c <- plot_ly(
x = c("giraffes", "orangutans", "monkeys"),
y = c(20, 14, 23),
name = "SF Zoo",
type = "bar") %>%
layout(xaxis = xform,
xaxis = list(title = "x"),
yaxis = list(title = "y"))
... this adds the axis title but x-axis now in the wrong order:
d <- plot_ly(
x = c("giraffes", "orangutans", "monkeys"),
y = c(20, 14, 23),
name = "SF Zoo",
type = "bar") %>%
layout(xaxis = list(xform, title = "x"),
yaxis = list(title = "y"))
I can't find any examples of others having this issue via search, so it's probably embarrassingly straightforward -- really appreciate any help.
CodePudding user response:
Try xaxis = append(xform, list(title = "x"))
or xaxis = c(xform, list(title = "x"))
.
xform <- list(categoryorder = "array",
categoryarray = c("giraffes",
"orangutans",
"monkeys"))
plot_ly(
x = c("giraffes", "orangutans", "monkeys"),
y = c(20, 14, 23),
name = "SF Zoo",
type = "bar") %>%
layout(xaxis = append(xform,
list(title = "x")),
yaxis = list(title = "y"))
If you use an argument more than once in the layout
function, like you did with plot c. Plotly seems to only recognize the first time the argument is used and ignores the duplicated ones. Therefore your plot has just an ordered xaxis but no title.
In plot d, you created a list of lists. If the write out your code junk, xaxis = list(xform, title = "x")
, it looks like this:
xaxis = list(list(categoryorder = "array",
categoryarray = c("giraffes",
"orangutans",
"monkeys")),
title = "x")
But you need this structure:
xaxis = list(categoryorder = "array",
categoryarray = c("giraffes",
"orangutans",
"monkeys"),
title = "x")
So you want to append your lists xform
and list(title = "x")
with the append
or c
function instead of the list
function.