dreamRs / apexcharter

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

fill colors in bar chart #40

Closed bklingen closed 3 years ago

bklingen commented 3 years ago

Getting a bar chart with different colored bars is harder than you think, and the end result is still not satisfying as it shows empty (NA) labels: A natural (by ggplot2 standards) approach is to try:

library(apexcharter)
plotdata <- data.frame(x=c("a","b"), counts=5:6, color=1:2)
apex(
  data = plotdata, 
  type = "column",
  mapping = aes(x = x, y = counts, fill = color)
)

but this "drops" the b category and produces image

One can complete the plotdata through

library(tidyr)
plotdata1 <- complete(plotdata, x, color)

and then get two different colors for the two bars

apex(
  data = plotdata1, 
  type = "column",
  mapping = aes(x = x, y = counts, fill = color)
)

but there are empty bars at each category on the x-axis (because of the NA's generated in complete): image

Ideally, I was hoping code like

apex(
  data = plotdata, 
  type = "column",
  mapping = aes(x = x, y = counts, fill = color)
) %>%
ax_colors(c("red","orange"))

would give two bars, the one over "a" in one red, the other over "b" in orange. Instead, I get: image

But perhaps I don't quite understand how to get this with apexcharter. Thanks! Bernhard

pvictor commented 3 years ago

Hello,

Yes there's a bug somewhere with your first example, I'll investigate.

In your last example, bars are gray because colors names don't work, you have to use hex code.

To achieve what you desire, I see 2 options:

library(apexcharter)
plotdata <- data.frame(x=c("a","b"), counts=5:6, color=1:2, fillColor = c("#FE2E2E", "#FF8000"))
apex(
  data = plotdata, 
  type = "column",
  mapping = aes(x = x, y = counts, fillColor = fillColor)
)

image

library(tidyr)
plotdata1 <- complete(plotdata, x, color)
apex(
  data = plotdata1, 
  type = "column",
  mapping = aes(x = x, y = counts, fill = color)
) %>% 
  ax_chart(stacked = TRUE) %>%
  ax_colors(c("#FE2E2E", "#FF8000"))

image

Hope it helps !

Victor

bklingen commented 3 years ago

Wonderful, works perfectly, thanks!