Hi and thanks for reading me
I'm working with a bar chart on R with the Echarts4r package, but I want to do a waterfall chart and I don't find an option to do a plot like the following on the image:
It's possible to do this chart type? The code I'm using for now is the following:
library(echarts4r)
df <- data.frame(
var = sample(LETTERS, 5),
value = rnorm(5, mean = 200, sd = 100)
)
df |>
e_charts(var) |>
e_bar(value)
Not sure whether echarts4r offers an option out of the box but with some data wrangling you could achieve your result as a stacked bar chart like so:
Disclaimer: I borrowed the basic idea from here.
library(echarts4r)
library(dplyr)
set.seed(42)
df <- data.frame(
var = sample(LETTERS, 5),
value = rnorm(5, mean = 200, sd = 100)
)
df |>
mutate(bottom = cumsum(dplyr::lag(value, default = 0)),
bottom = ifelse(value < 0, bottom + value, bottom),
top = abs(value)) |>
e_charts(var) |>
e_bar(bottom, stack = "var", itemStyle = list(color = "transparent", barBorderColor = "transparent")) |>
e_bar(top, stack = "var")
Related
I was using Highchart to plot some time series and wanted to add some annotation to the plot to highlight some key points. I knew putting the cursor on the graph can pop up the context, however, some automatic graph generation is needed and hence annotating is the best approach.
And I did that, with the last line in the code below. However, the effect is not what I expected. The text was located at the bottom left corner, not located at the right horizontal position yet the vertical position is right. The time series are created using xts library, which means the horizontal axis is simply the date data structure, nothing fancy. xValue is specified as the 900th element of all the time points which have a total length of 1018, so the 900th time point must be in the second half of the graph.
Anyone knows how I can put the annotation at the right location? Many thanks.
hc <- highchart(type = "stock") %>%
hc_title(text = "Some time series") %>%
hc_add_series(x, color='green', name="x", showInLegend = TRUE) %>%
hc_add_series(y, color='red', name="y", showInLegend = TRUE) %>%
hc_add_series(z, color='blue', name="z", showInLegend = TRUE) %>%
hc_navigator(enabled=FALSE) %>%
hc_scrollbar(enabled=FALSE) %>%
hc_legend(enabled=TRUE, layout="horizontal") %>%
hc_annotations(list(enabledButtons=FALSE, xValue = index(x)[900], yValue = -5, title =list(text = "Hello world! How can I make this work!")))
hc
The data can be roughly generated using the following script:
dt <- seq(as.Date("2014/1/30"), as.Date("2018/2/6"), "days")
dt <- dt[!weekdays(dt) %in% c("Saturday", "Sunday")]
n <- length(dt)
x <- xts(rnorm(n), order.by=dt)
y <- xts(rnorm(n), order.by=dt)
z <- xts(rnorm(n), order.by=dt)
Let's star with the #kamil-kulig example, this will be a little out of R world but I want to give some justification if you don't mind.
If we see annotations options is not a object but a list of object(s), so in highcharter is implemented the hc_add_annotation function.
Now, you are using a old version of highcharter. Highcharter devlopment version is using v6 of highchartsJS which made some changes: before the annotations.js was a pluging now is included as a module with some changes in the names of arguments.
Example I: Simple
The example by Kamil Kulig is replicated doing:
highchart(type = "stock") %>%
hc_add_annotation(
labelOptions = list(
backgroundColor = 'rgba(255,255,255,0.5)',
verticalAlign = 'top',
y = 15
),
labels = list(
list(
point = list(
xAxis = 0,
yAxis = 0,
x = datetime_to_timestamp(as.Date("2017/01/02")),
y = 1.5
),
text = "Some annotation"
)
)
) %>%
hc_xAxis(
minRange = 1
) %>%
hc_add_series(
pointStart = start,
pointInterval = day,
data = c(3, 4, 1)
)
Example II: With your data
Be careful in the way you add the x position. Highcharter include a datetime_to_timestamp function to convert a date into a epoch/timestap which is required for highcharts.
library(xts)
dt <- seq(as.Date("2014/1/30"), as.Date("2018/2/6"), "days")
dt <- dt[!weekdays(dt) %in% c("Saturday", "Sunday")]
n <- length(dt)
x <- xts(rnorm(n), order.by=dt)
y <- xts(rnorm(n), order.by=dt)
z <- xts(rnorm(n), order.by=dt)
highchart(type = "stock") %>%
hc_title(text = "Some time series") %>%
hc_add_series(x, color='green', name="x", showInLegend = TRUE) %>%
hc_add_series(y, color='red', name="y", showInLegend = TRUE) %>%
hc_add_series(z, color='blue', name="z", showInLegend = TRUE) %>%
hc_navigator(enabled=FALSE) %>%
hc_scrollbar(enabled=FALSE) %>%
hc_legend(enabled=TRUE, layout="horizontal") %>%
hc_add_annotation(
labels = list(
list(
point = list(
xAxis = 0,
yAxis = 0,
x = datetime_to_timestamp(as.Date(index(x)[900])),
y = 1
),
text = "Hello world! How can I make this work!"
)
)
)
I use plotly library in R.
I want to have two symmetric bar charts. Something like that:
But I have :
plot_ly(x= customer_age_sex$POP,y=customer_age_sex$AGE,color=customer_age_sex$CIVILITE) %>%
add_bars(orientation = 'h')
How can I change the orientation of the orange bar plot to be symmetric with the other?
Thanks a lot for your help.
There is a good example here. Note that this requires the values to be negative for one of the genders. If that is not the case, you could do the following:
set.seed(1)
age <- rep(1:90, 2)
sex <- rep(c('Monsieur', 'Madame'), each = 90)
pop <- rep(seq(100,11),2) + runif(180,0,10)
df <- data.frame(age, sex, pop) %>%
mutate(abs_pop = pop) %>%
mutate(pop =ifelse(sex=='Monsieur',-pop,pop))
df %>%
plot_ly(x= ~pop, y=~age,color=~sex) %>%
add_bars(orientation = 'h', hoverinfo = 'text', text = ~abs_pop) %>%
layout(bargap = 0.1, barmode = 'overlay',
xaxis = list(tickmode = 'array', tickvals = c(-1000, -500, 0, 500, 1000),
ticktext = c('1000', '500', '0', '500', '1000')))
Hope this helps!
I am plotting a pie chart using highcharter. when the mouse hover on each slice< it only shows just one value, but I want to add another value so that it shows two!
here is a sample code:
in my code you see that it is ploting the data using just A column and B column, but I want it to show C column as additional information as the mouse hover on slices.
library(highcharter)
A <- c("a", "b", "c", "d")
B <- c(4, 6, 9, 2)
C <- c(23, 26, 13, 15)
df <- data.frame(A, B, C)
highchart() %>%
hc_chart(type = "pie") %>%
hc_add_series_labels_values(labels = df$A, values = df$B)%>%
hc_tooltip(crosshairs = TRUE, borderWidth = 5, sort = TRUE, shared = TRUE, table = TRUE,
pointFormat = paste('<b>{point.percentage:.1f}%</b>')
) %>%
hc_title(text = "ABC",
margin = 20,
style = list(color = "#144746", useHTML = TRUE))
To my knowledge, the solution proposed by #ewolden does not work in highcharter.
A simple and flexible solution for setting additional information to the tooltip of a highcharter pie is the following:
library(highcharter)
A <- c("a", "b", "c", "d")
B <- c(4, 6, 9, 2)
C <- c(23, 26, 13, 15)
df <- data.frame(A, B, C)
# A modified version of the "hc_add_series_labels_values" function
# The "text" input is now available
myhc_add_series_labels_values <- function (hc, labels, values, text, colors = NULL, ...)
{
assertthat::assert_that(is.highchart(hc), is.numeric(values),
length(labels) == length(values))
df <- dplyr::data_frame(name = labels, y = values, text=text)
if (!is.null(colors)) {
assert_that(length(labels) == length(colors))
df <- mutate(df, color = colors)
}
ds <- list_parse(df)
hc <- hc %>% hc_add_series(data = ds, ...)
hc
}
# Set the "text" input in myhc_add_series_labels_values
# point.text is now available inside pointFormat of hc_tooltip
highchart() %>%
hc_chart(type = "pie", data=df) %>%
myhc_add_series_labels_values(labels=A, values=B, text=C) %>%
hc_tooltip(crosshairs=TRUE, borderWidth=5, sort=TRUE, shared=TRUE, table=TRUE,
pointFormat=paste('<br><b>A: {point.percentage:.1f}%</b><br>C: {point.text}')) %>%
hc_title(text="ABC", margin=20, style=list(color="#144746", useHTML=TRUE))
With this solution we can print the content of two or more variables inside the tooltip. Below we add a variable D to the df dataset and visualize it in the tooltip:
D <- c("Mars", "Jupiter", "Venus", "Saturn")
df <- data.frame(A, B, C, D)
txt <- paste("C:",C," <br>D:", D)
highchart() %>%
hc_chart(type="pie", data=df) %>%
myhc_add_series_labels_values(labels=A, values=B, text=txt) %>%
hc_tooltip(crosshairs=TRUE, borderWidth=5, sort=TRUE, shared=TRUE, table=TRUE,
pointFormat=paste('<br><b>A: {point.percentage:.1f}%</b><br>{point.text}')) %>%
hc_title(text = "ABC", margin = 20, style = list(color = "#144746", useHTML = TRUE))
You can make a chart with custom names in highcharts like so:
http://jsfiddle.net/zh65suhm/.
That is, changing your tooltip to the following:
'<b>{point.percentage:.1f}%</b><br>Custom point: <b>{point.customData}</b>'
Where each point has its own customData value.
I have not used highcharter, but looking at the API it might be possible to some work with this:
hc_add_series(favorite_bars, "pie", hcaes(name = bar, y = percent), name = "Bars") %>%
Potentially this could work:
hc_add_series(favorite_bars, "pie", hcaes(name = bar, y = percent, customData = variable_with_customdata), name = "My pie") %>%
Hopefully this will help you out.
I'm trying to create a scatter plot in highcharts shiny R but I need to give a different color to points, individually. Consider for instance the following example:
library("MASS")
dscars <- round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2)
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{series.color};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list.parse2(as.data.frame(dscars)),
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")
My objective is to give to this 20 points, an unique color.
I tried to set the "fillColor" inside marker list as also as to define the color of the series, both with a vector of 20 colors but I had no success.
Can any one give me a hint?
Thank you
In highcharts (the highcharter) the point can be given as other parameter, same as x and y. So first
library("MASS")
dscars <- round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2)
dscars <- as.data.frame(dscars)
names(dscars) <- c("x", "y") # it's better give a named list IMHO
dscars$color <- colorize(1:nrow(dscars))
colorizeis a function to create a color vector given other vector. In this case the input vector is a sequence (no repeated) so the output will be differents colors. But if you want yo can use your own colors.
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{point.color};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list_parse(dscars),
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")
Note we used:
color:{point.color}; in the poinFormat, beacuse every point has its own color in the color accesor.
I used list_parse which parse the data frame in a named list instead of unnamed list so highcharts understand how to use the data. list_parse is the same list.parse3 for old version of highcharts.
Hope it helps.
Is this what you want?
rm(list = ls())
library(highcharter)
library(MASS)
dscars <- data.frame(round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2))
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{colorByPoint:true};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list.parse2(as.data.frame(dscars)),colorByPoint = TRUE,
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")
I am trying to create an interactive Version of this plot:
So far I have the following code that creates an interactive plot but is not exactly what I am looking for:
#Create Data
library(ggvis)
set.seed(123)
tdat <- data.frame(group = rep(LETTERS[1:2], each = 50),
time = rep(seq(from = as.Date("2010-01-01"), length.out = 50, by = "day"), 2),
val = c(cumsum(rnorm(50)) + 100,
cumsum(rnorm(50)) + 100))
# ggvis Code
# Function for the tooltip
getData <- function(dat){
paste(paste("Time:", as.character(dat$time)),
paste("Group:", as.character(dat$group)),
paste("Value:", dat$val),
sep = "<br />")
}
# Visualisation
tdat %>% ggvis(~time, ~val, stroke = ~group) %>% layer_lines(strokeWidth := 1) %>%
layer_points(size = 1, fill = ~group) %>% add_tooltip(getData)
This results in the following plot:
There are however some issues:
1) I don't want to have points, just lines. Without the layer_points, there are no tooltips...
2) The variable time is a date but shows up as an integer. How can I fix the ugly number?
Thank you very much.
Edit
The field of the tooltip can be formated to date if it is coerced to a char before calling the ggvis function but it introduces other issues. For example, the x-axis does not shown properly.
I found a solution for both:
#Create Data
library(ggvis)
set.seed(123)
tdat <- data.frame(group = rep(LETTERS[1:2], each = 50),
time = rep(seq(from = as.Date("2010-01-01"), length.out = 50, by = "day"), 2),
val = c(cumsum(rnorm(50)) + 100,
cumsum(rnorm(50)) + 100))
For the getData function a bit of reverse engineering made me find the solution. Apparently if you divide the numeric date by 86400000 and add the origin of 1970-01-01 makes it work.
# ggvis Code
# Function for the tooltip
getData <- function(dat){
paste(paste("Time:", as.Date(dat$time/86400000, origin='1970-01-01') ),
paste("Group:", as.character(dat$group)),
paste("Value:", dat$val),
sep = "<br />")
}
As for the points, just setting the opacity to zero makes it work:
# Visualisation
tdat %>% ggvis(~time, ~val, stroke = ~group) %>% layer_lines(strokeWidth := 1) %>%
layer_points(size = 1, fill = ~group, opacity := 0) %>% add_tooltip(getData)
Ouput:
Sorry for the bad output but this was the best I could get via a print screen.