[R] Plot_ly bar plots - bars span sevral x values when there are missing values.

nevil amos nev||@@mo@ @end|ng |rom gm@||@com
Tue Mar 9 08:42:21 CET 2021


I need to plot a number of bar charts as part of a shiny app.

I am using ploty ly

x and y  values are both numeric x being consecutive integer values.

there are often missing values in the data I wish to plot - each plot needs
to have a fixed x range.

When there are more than a few missing values  the bars for the remaining
values are being plotted much wider spanning several x values ( see example
2)

curiously when there is a single remaining value the bar width is correct
(example 3)

how can I maintain a constant bar width regardless of number of missing
values? I cannot find a bar-width setting.


df<-data.frame(x=1:20,y=rnorm(20)^2)

#twenty bars each centred above a single x value:
df%>%plot_ly(
  x =  ~ x,
  y =  ~ y,
  type = "bar")%>%
  layout(xaxis = list(range = c(0,20)),
         title = "example 1")

# this produces wide bars first one spread x= 0-6 second x= 8-14
# expected two column same width as in example 1 centred above x=3 and x=11
df[c(3,11),]%>%plot_ly(
  x =  ~ x,
  y =  ~ y,
  type = "bar")%>%
  layout(xaxis = list(range = c(0,20)),
         title = "example 2 column width expands across multiple x values")

# when only a single bar is present it is again the correct width - in this
case centred above x=3
df[3,]%>%plot_ly(
  x =  ~ x,
  y =  ~ y,
  type = "bar")%>%
  layout(xaxis = list(range = c(0,20)),
         title = "example 3 correct columns again")

	[[alternative HTML version deleted]]



More information about the R-help mailing list