0
votes

I'm trying to add a plot to my shiny dashboard. The y-axis variable is a proportion and I want to format this as a percentage. I've discovered I can do it using the tickformat feature in the yaxis setting of the layout. However, since the percentages in my chart are all so low, I've noticed a couple of quirks.

Firstly, both the y-axis and the actual values when you hover over the data points are rounded to 0 decimal places. So both 0.0287 and 0.275 appear as 0.3 for example, even though their actual position on the chart is slightly different, reflecting the true underlying value.

Secondly, when the y-axis range is so small and is also round to 0 decimal places by default, it shows the same value at multiple ticks, and the tick intervals are also not intuitive.

I have provided example code below, adapted from the example on the plotly site. (I just changed the values to smaller values).

You can see the chart it produces gives tick marks show 2%, 3%, 3%, 4%, 4%, 5%, 5%, 5%, 6%. First problem with this is it's misleading, secondly you can see there's 3x 5% there, but only 2x of the others, so it seems like it's not even doing a sensible gap like 4.5%, 5%, 5.5%, etc., but rather something unintuitive based on the data values.

library(plotly)

fig <- plot_ly(
  type = "scatter",
  x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 
  y = c(0.0185, 0.0382, 0.0561, 0.0463, 0.0596, 0.048, 0.0287, 0.0275, 0.0243, 0.0429, 0.0450, 0.0391), 
  mode = "markers+lines") 
fig <- fig %>%
  layout(
    yaxis = list(
      tickformat = "%"
    ))

fig

In summary:

How do I...

  1. Specify how to round the percentages?
  2. Ensure that it doesn't space tick marks at such an interval that the same rounded value appears more than once?
  3. Ensure that it chooses an intuitive tick interval when looking at decimal places (such as 0.5 or 0.25, rather than something silly like 0.37 for example)
2

2 Answers

1
votes

Using tickformat = ".2%" would solve (1. and 2.) in your case.

Explicitly defining tickvals (e.g. tickvals = seq(.02,.06, .01)) would answer (3.).

See https://plotly.com/r/reference/#Layout_and_layout_style_objects for more parameters.

Briefly, you could try:

  layout(
    yaxis = list(
      tickformat = ".1%",
      tickvals = seq(.02,.06, .005)
    ))

for example, or modify to your liking.

1
votes

Another way is to manually specify the tickvals and format the ticktext:

library(plotly)

fig <- plot_ly(
  type = "scatter",
  x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 
  y = c(0.0185, 0.0382, 0.0561, 0.0463, 0.0596, 0.048, 0.0287, 0.0275, 0.0243, 0.0429, 0.0450, 0.0391), 
  mode = "markers+lines") 
fig <- fig %>%
  layout(
    yaxis = list(
      tickvals=seq(0,max(y),.005),ticktext=paste0(seq(0,max(y),.005)*100,"%")
    ))

fig