Ordering the stacking in a highcharts bar chart in R - r

I am trying to make a stacked bar chart, where de values that are being stacked have a specific order.
I understand that you can do this by ordering the series as they come in. But I am adding all series at once, so I'm not sure how this would work.
I have tried ordering the dataframe itself, but this does not appear to do anything.
I've also read about indexing, but I haven't been able to get that to work.
An example:
# create data frame
cat1 <- c('cat','dog','cat','bunny','dog','bunny')
cat2 <- c('brown','grey','grey','grey','brown','brown')
value <- c(15,80,85,36,20,64)
# Join the variables to create a data frame
df <- data.frame(cat1,cat2,value)
df
#create barchart
hchart(df, type = 'bar', hcaes( y = value, group=cat2, x = cat1)) %>%
hc_plotOptions(series = list(stacking = "normal"))
This creates a barchart with grey first and brown second. But I would like to set the order myself. Is this possible?
Off course, I can split my dataframe into separate datasets, but I also have charts where I have many categories that need to be stacked. I would rather not add all of these separately.

You can change levels before plotting -
> df <- within(df, cat2 <- factor(cat2, levels=c("grey","brown")))
> hchart(df, type = 'bar', hcaes( y = value, group=cat2, x = cat1)) %>%
hc_plotOptions(series = list(stacking = "normal"))

You can define index property in your series. Here you have JS example of this:
series: [{
name: 'First',
data: [5, 6, 4],
index: 0
}, {
name: 'Second',
data: [1, 3, 2],
index: 4
}, {
name: 'Third',
data: [6, 7, 2],
index: 1
}, {
name: 'Fourth',
data: [11, 13, 12],
index: 3
}, {
name: 'Fifth',
data: [9, 9, 2],
index: 2
}]
jsFiddle: https://jsfiddle.net/BlackLabel/uj7qmp3d
API: https://api.highcharts.com/highcharts/series.bar.index

Related

Use hc_tooltip in R Highchart to give format to different lines

I'm trying to format two series of my graph in highchart. The first graph is a serie and the another is a %change. So I want to format each serie using "hc_tooltip" argument. A simplified version of my code to show my problem is the next:
a <- c(30, 40, 10, 40, 80)
b <- c(3, 4, -1, -4, -8)
d<-cbind(a,b)
dt <- seq(as.Date("2018-01-01"), as.Date("2018-01-05"), by = "days")
ts <- xts(d, dt )
highchart(type="stock") %>%
hc_add_series(ts$a,
type = "line",
color="black") %>%
hc_add_series(ts$b,
type = "lollipop",
color="red") %>%
hc_tooltip(pointFormat = '<b>{point.a.name}</b>
{point.y.a:.4f}')%>%
hc_tooltip(pointFormat = '<b>{point.b.name}</b>
{point.y.b:.4f}%')
Like I hoped, It's not working. I want I can see the data from the first serie like integer and the second like % in the graph when I put the mouse in the serie. How can I achieve that?
To achieve that, you need to use the tooltip.formatter with the relevant function
Example:
hc_tooltip(formatter = JS("function () {
if (this.series.name === "A") {
return `<b>${this.series.name}</b></br>${this.y}`
} else if (this.series.name === "B") {
return `<b>${this.series.name}</b></br>${this.y}%`
}}")
JS Demo:
https://jsfiddle.net/BlackLabel/zqyp85ag/
API Reference:
https://api.highcharts.com/highcharts/tooltip.formatter

In Highchart R package how to display multiple line charts but Starting with only 2 lines

I want to plot a highchart plot with 5 countries.
But I would like to start the chart with only "Chile" and "Argentina" lines.
And then I would let the use add the others countries interactively by clicking on the others countries legends.
Is it possible?
library(highcharter)
library(gapminder)
gapminder %>% filter(country == c("Chile","Argentina","Peru","Brazil","Portugal")) %>%
hchart("line",
hcaes(x = year, y = pop, group = country))
One way to do this is to load the countries in two steps, one marked visible = FALSE.
Unfortunately, this makes the groups out of alphabetical order, so it would take some manual work with more layers to control both the ordering and the initial visibility.
gap_vis <- subset(gapminder, country %in% c("Chile","Argentina"))
gap_hid <- subset(gapminder, country %in% c("Peru","Brazil","Portugal"))
hchart(gap_vis, "line", hcaes(x = year, y = pop, group = country)) %>%
hc_add_series(gap_hid, "line", hcaes(x = year, y = pop, group = country),
visible = FALSE)
You need to only set visible: false for the proper series. Example in pure JS:
series: [{
name: 'Chile',
data: [...]
}, {
name: 'Argentina',
data: [...]
}, {
name: 'Peru',
data: [...],
visible: false
}, {
name: 'Brazil',
data: [...],
visible: false
}, {
name: 'Portugal',
data: [...],
visible: false
}]
Live demo: http://jsfiddle.net/BlackLabel/4ebnj0Lq/
API Reference: https://api.highcharts.com/highcharts/series.line.visible

Customize legend entries in pie chart using R Plotly

I am trying to make a pie chart in R using plotly. I have a tibble (df) with 4 columns - (1) an observation (x), (2) value of the observation (y), (3) category of the observation (cat), and (4) color of each observation (colors). Colors are unique for each category (every observation within the same category will share the same color). I need each segment of the pie chart to represent each observation with the size of the segment corresponding to the value of the observation. I also need the segments to be colored by their unique category color. I have been able to build such a pie chart.
I am, however, struggling with how to customize the legend. Using showlegend=TRUE shows each observation with it's color. I need the legend to showcase each unique category with its distinct color. I would really appreciate it if someone could help me out with this.
Here is some dummy code that models this problem -
# Load packages
library(tidyverse)
library(plotly)
# Initialize variables
df = NULL
x = c("apple", "John", "dog", "lion", "strawberry", "Liz",
"cat", "peach", "banana", "elephant", "pear", "tiger")
y = c(1, 1, 3, 5, 4, 3, 6, 4, 1, 2, 1, 6)
cat = c("fruit", "person", "animal", "animal", "fruit", "person",
"animal", "fruit", "fruit", "animal", "fruit", "animal")
colors = NULL
# Define colors
for (i in 1:length(cat)) {
if (cat[i] == "fruit") {
color = "#FFD700"
} else if (cat[i] == "animal") {
color = "#FB8072"
} else {
color = "#D3D3D3"
}
colors = c(colors, color)
}
# Create data frame
df = as_tibble(cbind(x, y, cat, colors))
# Sort data frame
df = df[order(df$cat, df$x), ]
# Define colors for pie chart
pie_colors = as.character(df$colors)
# Define margins for pie chart
margins = list(l=50, r=50, b=125, t=125)
# Build the pie chart
pie_plt = plot_ly(data=df,
values=~y,
labels=~x,
type="pie",
textinfo="label+percent",
sort=FALSE,
marker=list(colors=pie_colors,
line=list(color="black", width=1))) %>%
layout(autosize=FALSE, margin=margins, showlegend=TRUE)
# Show pie chart:
pie_plt

Rcharts: plot only shows first character of label

I recently switched from ggplot to Rcharts and have a fairly simple question about the labels.
Sample data
data_1 <- data.table(Filter = c('Filter 1', 'Filter 2'),
Amount = c(100, 50))
data_2 <- data.table(Filter = c('Filter 1'),
Amount = c(100))
Plots
hPlot(Amount ~ Filter, data = data_1, type = 'bar', group.na = 'NA\'s')
hPlot(Amount ~ Filter, data = data_2, type = 'bar', group.na = 'NA\'s')
Question:
Why do we see the correct label in the first plot, but only the first letter of the label in the second plot? This issue always occurs when the number of rows = 1 (as it is in data_2).
Does anyone has a quick fix / workaround?

rCharts nvd3 library force ticks

I would like to force all tick marks and tick labels to appear along the axis in an rCharts nPlot from the nvd3 library. I have tried several approaches without success.
This is the default behaviour:
df <- data.frame(x = 1:13, y = rnorm(13))
library(rCharts)
n <- nPlot(data = df, y ~ x, type = 'lineChart')
n$yAxis(showMaxMin = FALSE)
I would like to have all data in 1:13 show along the x axis.
Ultimately, I have custom tickmarks I want to show equally-spaced with the following replacement:
n$xAxis(tickFormat = "#! function (x) {
ticklabels = ['0-1000', '1000-1500', '1500-1700', '1700-1820', '1820-1913',
'1913-1950', '1950-1970', '1970-1990', '1990-2012', '2012-2030',
'2030-2050', '2050-2070', '2070-2100']
return ticklabels[x-1];
} !#")
I hope it is clear why I want to have all tick marks and labels printed (and equally spaced).
To give an idea of the finished product, here is a ggplot2 impression:
library(ggplot2)
df <- data.frame(x = c('0-1000', '1000-1500', '1500-1700', '1700-1820', '1820-1913',
'1913-1950', '1950-1970', '1970-1990', '1990-2012', '2012-2030', '2030-2050',
'2050-2070', '2070-2100'), y = rnorm(13), z = "group1")
ggplot(data = df, aes(x = x, y = y, group = z)) + geom_line()
Here are several things I have tried, based on several suggestions I found here and there: neither work.
Based on my reading of the docs, I thought this would work:
n$xAxis(tickFormat = "#! function (x) {
return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13][x-1];
} !#")
I also tried this, on the off chance:
n$xAxis(ticks = 13)
I also tried to combine tickValues and tickFormat but with no success.
I also thought about writing a script, but again my understanding of the nvd3 library was insufficient.
n$setTemplate(afterScript =
"<script>
var chart = nv.models.lineChart();
var newAxisScale = d3.scale.linear();
.range(d3.extent(chart.axes[0]._scale.range()))
.domain([1, d3.max(chart.axes[0]._scale.domain())])
chart.axes[0].shapes.call(
d3.svg.axis()
.orient('bottom')
.scale(newAxisScale)
.ticks(13)
//.tickValues()
//.tickFormat(d3.format())
).selectAll('text')
.attr('transform','')
</script>"
)
None of these report errors in the console, but none of them modify the appearance of the first plot above.
It turns out I was not correctly setting tickValues as I got the syntax confused with tickFormat. Here is an rCharts solution. The corresponding d3 or nvd3 solution should be easy to deduce.
n <- nPlot(data = df, y ~ x, type = 'lineChart')
n$yAxis(showMaxMin = FALSE)
n$addParams(height = 500, width = 1000)
n$xAxis(tickValues = "#! function (x) {
tickvalues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
return tickvalues;
} !#")
n$xAxis(tickFormat = "#! function (x) {
tickformat = ['0-1000', '1000-1500', '1500-1700', '1700-1820', '1820-1913',
'1913-1950', '1950-1970', '1970-1990', '1990-2012', '2012-2030', '2030-2050',
'2050-2070', '2070-2100'];
return tickformat[x-1];
} !#")
n
Notice how the code has tickvalues in tickValues but tickformat[x-1] in tickFormat.

Resources