dreamRs / apexcharter

:bar_chart: R Htmlwidget for ApexCharts.js
https://dreamrs.github.io/apexcharter
Other
138 stars 15 forks source link

[Feature Request] Text annotation with add_text #49

Closed bklingen closed 3 years ago

bklingen commented 3 years ago

Would it be possible to add something like an add_text to complement add_vline, add_hline and add_point? It seems like the annotations definitions in apexchart allow for a text label:

annotations: {
...

  texts: [{
    x: 0,
    y: 0,
    text: '',
    textAnchor: 'start',
    foreColor: undefined,
    fontSize: '13px',
    fontFamily: undefined,
    fontWeight: 400,
    appendTo: '.apexcharts-annotations',
    backgroundColor: 'transparent',
    borderColor: '#c2c2c2',
    borderRadius: 0,
    borderWidth: 0,
    paddingLeft: 4,
    paddingRight: 4,
    paddingTop: 2,
    paddingBottom: 2,
  }],

...
}

I tried with ax_annotations (texts = list(list(...))), but to no avail:

library(ggplot2)
library(apexcharter)

data("economics", package = "ggplot2")

apex(
  data = tail(economics, 200),
  mapping = aes(x = date, y = uempmed),
  type = "line"
) %>% 
  ax_annotations(
    yaxis = list(list(
      y = 11.897,
      borderColor = "firebrick", 
      opacity = 1,
      label = list(
        text = "Mean uempmed",
        position = "left", 
        textAnchor = "start"
      )
    ))
  ) %>%
ax_annotations(
  texts = list(list(
    x = htmlwidgets::JS("new Date('1 Mar 2007').getTime()"),
    y = 15,
    text = "A Text Label"
  ))
)
pvictor commented 3 years ago

I think annotations.texts is used internally to place labels next to point/line annotations (see the appendTo argument). If you just want to add text, the easiest way I think is to use a point and make it transparent, e.g. :

library(ggplot2)
library(apexcharter)

data("economics", package = "ggplot2")
apex(
  data = tail(economics, 200),
  mapping = aes(x = date, y = uempmed),
  type = "line"
) %>% 
  add_event_marker(
    when = "2007-03-01",
    y = 15,
    label = label("A Text Label", offsetX = 0, offsetY = 15),
    color = "transparent",
    fill = "transparent"
  )
bklingen commented 3 years ago

Wonderful, thanks! And for other plot types, one can just use add_point with x and y coordinates and size=0 to add an invisible point plus a label.