Add gridlines between main gridlines in a plotly bar chart

Viewed 2925

I would like to add between the main gridlines of the chart four lines with a more light color like in the example below. How could I specify them?

enter image description here

library(plotly)
co<-c("AL","FG","GH","HJ","FT")
va<-c(1000000,1000000,1000000,5000000,5000000)
cova<-data.frame(co,va)

fig1 <- plot_ly(cova, x = ~co, y = ~va,
                type = 'bar'
                
                
                
                
) 
fig1%>% layout(showlegend=F,
               font = list(color = '#a2a2a2'),
               yaxis = list(title="",
                            showgrid = T,gridcolor = "#a2a2a2", showline = FALSE, showticklabels = TRUE, domain= c(0, 0.85)),
               xaxis = list(title="",zeroline = FALSE, showline = T,showticklabels = F,tickangle=45, showgrid = FALSE))
  
1 Answers

updated

The answer is already available on SO major and minor tick marks

  • adapt to work with bar plots
  • adapt so that second trace does not create grid lines in same location as major grid lines
library(plotly)
library(comprehenr)

co<-c("AL","FG","GH","HJ","FT")
va<-c(1000000,1000000,1000000,5000000,5000000)
cova<-data.frame(co,va)

fig1 <- plot_ly(cova, x = ~co, y = ~va,
                type = 'bar'
) 
fig1 <- fig1%>% layout(showlegend=F,
               font = list(color = '#a2a2a2'),
               yaxis = list(title="", showgrid = T,gridcolor = "#a2a2a2", showline = FALSE, showticklabels = TRUE, 
                            domain= c(0, 0.85)),
               xaxis = list(title="",zeroline = FALSE, showline = T,showticklabels = F,tickangle=45, showgrid = FALSE))

# plot additional transpareent bar on top of original bar
# give this "invisible" layer a different y-axis with ticks which are minor ticks
# this then generates gridlines,  that can be styles as you please
# NB - tickvals excludes major tickval using integer remainder logic in list comprehension
mtick <- 2*10**5 # minor ticks every 200k
fig1 %>% add_trace(x=~co, y=~va, yaxis="y2", marker=list(color='rgba(0,0,0,0)')) %>%
    layout(yaxis2=list( overlaying="y", 
                       tickvals=to_list(for(i in seq(0, max(cova$va), by=mtick) )  if (i%%10**6) i ), 
                           showticklabels=FALSE ))

enter image description here

previous iteration of question answer

Have created R environment. As noted solution same in both python and r. it's just language syntax sugar that differentiates them.

  • a gridline is drawn on every tickval
  • ticktext controls values in the axis. Hence " " where you want a grid line, but no tick value. NB empty string gives a strange behaviour such that figure changes size
import plotly.graph_objects as go
import pandas as pd
import requests, io

dfall = pd.read_csv(io.StringIO(
    requests.get("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv").text))
dfall["date"] = pd.to_datetime(dfall["date"])
df_g = (dfall.loc[dfall.date.dt.month.ge(12) & dfall.date.dt.year.eq(2020) & dfall.continent.eq("Europe")]
 .groupby(["iso_code","location"]).agg({"new_deaths":"sum"})
 .sort_values("new_deaths", ascending=False)
 .head(8)
)

fig = go.Figure(data=[go.Bar(x=df_g.index.get_level_values("location"), y=df_g[c], 
                       marker={"color":df_g[c], "colorscale":"viridis"}) 
                for c in df_g.columns],
         layout={"title":"Total number of deaths in last month of 2020",
                "paper_bgcolor":'rgba(0,0,0,0)', "plot_bgcolor":'rgba(0,0,0,0)'})

fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='Purple', 
                 tickvals=[t for t in range(0, 20001, 1000)],
                 ticktext=[t/1000 if (t%5000)==0 else " " for t in range(0, 20001, 1000)]
                )
fig.update_xaxes(showline=True, linewidth=2, linecolor='black')


r

library(data.table)
library(plotly)
library(comprehenr)

dfall <- fread("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv")
df_g <- dfall[date %between% c("2020-12-01", "2020-12-31") & continent=="Europe", sum(new_deaths), by=location][order(-V1)][1:8] 
setnames(df_g, old="V1", new="new_deaths")

p <- plot_ly(df_g, x=~location, y=~new_deaths, type="bar", color=~new_deaths, colors="viridis") %>%
    layout(yaxis=list(showgrid=TRUE, 
                      gridwidth=1, 
                      gridcolor='Purple', 
                      ticktext=to_list(for(t in 0:20) if (t%%5!=0) " " else t),
                      tickvals=c(0:20)*1000),
          xaxis=list(showline=TRUE, linewidth=2, linecolor='black'))


p
Related