fill colors in bar chart
bklingen opened this issue · comments
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
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
):
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:
But perhaps I don't quite understand how to get this with apexcharter.
Thanks!
Bernhard
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:
- Use special aesthetic
fillColor
:
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)
)
- use
fill
aes like you did but with stacked bars:
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"))
Hope it helps !
Victor
Wonderful, works perfectly, thanks!