Search code examples
rtranslationlegendlabelrbokeh

r bokeh chart legend - placed poorly move


Bokeh Chart with ugly legend placementI have been working in flexdashboards using rbokeh to draw some dynamic graphs. Because this is a bar chart mapped to categorical data in the variable Classification, I am unable to manually create a legend, which is fine because rbokeh does it automatically.

However, I am having some issues with the legend and labeling:

  1. It is placed horribly, I would like to tell r to place in the upper left hand corner to get it away from bars with content.

  2. I would like to drop the red ab_line into the legend and label it (using standard legend = will not work because of the mapped variables in the base chart

  3. This graph needs to be 508 compliant for translation, the flexdashboard is, as well as the bokeh tools on the left hand margin and the keys in the pop ups, but the values and labels remain in English. Does anyone have a way of making the charts responsive to google translate? I am fine if that involves editing the extruded page....I will just need more guidance in doing it there.

    figure(title=" Confirmed & Probable Cases by Year",width= 1400, height =350)%>% ly_bar(x=Year, y= count, position='stack', data=probConf, width=.9,hover=TRUE, legend=TRUE, color=Classification) %>% x_axis(label ='Year')%>% y_axis(label ='Cases')%>% ly_abline(v=17.5, legend=NULL, color = "red", width =1, alpha=.5)%>% [![enter image description here][1]][1]set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))


Solution

  • To answer number 1, you can use legend_location to specify the placement of the legend (see example below and note I replaced the probConf data with the lattice barley dataset so that it is reproducible for others).

    figure(title = " Confirmed & Probable Cases by Year", width = 1400,
      height = 350, legend_location = "top_left") %>%
      ly_bar(x = variety, y = yield, position = "stack", data = lattice::barley,
        width = 0.9, hover = TRUE, legend = TRUE, color = year) %>%
      x_axis(label = "Year") %>%
      y_axis(label = "Cases") %>%
      ly_abline(v = "Svansota:1", color = "red",  width = 1, alpha = 0.5) %>%
      set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))
    

    #2 is currently difficult to achieve in rbokeh but it should be more robust to situations like this (mixing mapped and user-defined legend entries) in the future. If ly_abline() were to accept data as an argument, you could use use a mapped variable for color to resolve the issue.

    One solution that isn't very pretty is to manually draw the bar chart polygons with ly_rect (one call to ly_rect for each classification) and use custom legend entries for those and then add a custom legend entry for ly_abline.

    I do not know the answer to #3.