R Programming: How to show data labels in rCharts? - r

I have a bar chart where I want to show the value of the bar above each bar. However, using showValues results in the plot not working. Any ideas?
data2plot <-data.frame(Status=c("Open","Closed","Blocked"),Count=c(200,300,400))
a <- nPlot(Count ~ Status, data = data2plot, type = "multiBarChart")
a$chart(showValues=TRUE)
a
I'm using nplot, the nvd3 version. I'm open to changing to something else if I need to.

You can change type to discreteBarChart. To format the values displayed, you can use valueFormat, which takes a Javascript function and applies it to the values. Here is some info on d3.format function.
library(rCharts)
a <- nPlot(Count ~ Status, data = data2plot, type = "discreteBarChart")
a$chart(showValues=TRUE)
a$chart(valueFormat="#!d3.format('d')!#")
a

Related

Is there a way to have a highlighted chart as well as have interactivity of selecting elements in R?

I have come across a beautiful chart on this webpage: https://ourworldindata.org/coronavirus and interested to know if we can build the same chart in R with functionality of having highlighted series as well as selecting any line on hovering ?
I have build static highlighted charts using gghighlight but those are not interactive.
Plotly can help in interaction but I think they don't work with gghighlight.
So how can we have the combination of both highlight and interactivity in charts as in the link shared on top ?
Is it possible to achieve same results in R ? It would be really helpful if someone could share an example or link that can help.
(UPDATE: May be I can manually highlight lines by creating a factor column instead of using gghighlight and then pass it to ggplotly but then can ggplotly or some other library provide similar results on hover ?)
(NOTE: Not looking for animation. Just need highlighted, hover over interactive chart)
Below is the snapshot of same chart hovered over US (This chart is also similar to the one shared in World Economic Forum many times.)
Using plotly you can use highlight() to achive this.
This is a slightly modified example from here:
library(plotly)
# load the `txhousing` dataset
data(txhousing, package = "ggplot2")
# declare `city` as the SQL 'query by' column
tx <- highlight_key(txhousing, ~city)
# initiate a plotly object
base <- plot_ly(tx, color = I("black")) %>%
group_by(city)
# create a time series of median house price
time_series <- base %>%
group_by(city) %>%
add_lines(x = ~date, y = ~median)
highlight(
time_series,
on = "plotly_hover",
selectize = FALSE,
dynamic = FALSE,
color = "red",
persistent = FALSE
)

plotly_POST: the plot appears in R Viewer, but not online

I'm trying to publish the plot online via these two lines of code in R:
library('plotly')
plot_ly(data = sampledata, x = date, y = id, type = 'bar')
plotly_POST(sampledata, filename = "Test", world_readable=TRUE)
It doesn't give me any errors or warnings and says "Success! Created a new plotly here ->"
The plot appears in R Viewer, but if I go to my plotly account (or follow the link), I see a blank graph like this:
Blank plotly bar chart
I previously was able to publish one graph online - but I don't recall changing anything in my code.
Any advice is much appreciated!
You'll have to send the whole figure:
p <- plot_ly(data = sampledata, x = date, y = id, type = 'bar')
plotly_POST(p, filename = "Test", world_readable=TRUE)
For a little more information on plotly_POST you can check out this reference: https://plot.ly/r/file-options/

Fix layout of plot(fevd()) function

I am trying to plot FEVD (forecast error variance decomposition) for my VAR analysis. As you can see on the image, the legend screws up the graph and information. as this is an automatically created legend, I don’t know how to reposition it. I do not know much yet about plotting in R.
The only code i use to get this is :
library(vars)
var <- VAR(varTable2 , p=4 , type = "both")
plot(fevd(var, n.ahead = 10 ))
Thanks in advance
Legends do not resize well in R. You have to set your plotting window first and then chart your data.
Here's how to do it in Windows. win.graph opens a blank plotting window of the specified width. In Unix/Linux, you should look at X11() and in Mac, at quartz(). You might also consider shorter variable names.
library(vars)
data(Canada)
colnames(Canada) <-c("Long column name1","Long column name2","Long column name3","Long column name4")
var <- VAR(Canada , p=4 , type = "both")
win.graph(width=13,height=8)
plot(fevd(var, n.ahead = 10 ))

Dimple dPlot color x-axis bar values in R

I'm attempting to set manual colors for Dimple dPlot line values and having some trouble.
d1 <- dPlot(
x="Date",
y="Count",
groups = "Category",
data = AB_DateCategory,
type = 'line'
)
d1$xAxis(orderRule = "Date")
d1$yAxis(type = "addMeasureAxis")
d1$xAxis(
type = "addTimeAxis",
inputFormat = "%Y-%m-%d",
outputFormat = "%Y-%m-%d",
)
The plot comes out looking great, but I would like to manually set the "Category" colors. Right now, it's set to the defaults and I cannot seem to find a method of manually setting a scale.
I have been able to set the defaults using brewer.pal, but I want to match other colors in my report:
d1$defaultColors(brewer.pal(n=4,"Accent"))
Ideally, these are my four colors - the category values I'm grouping on are R, D, O and U.
("#377EB8", "#4DAF4A", "#E41A1C", "#984EA3"))
If I understand correctly, you want to make sure R is #377EB8, etc. To match R, D, O, U consistently to the colors especially across multiple charts, you will need to do something like this.
d1$defaultColors = "#!d3.scale.ordinal().range(['#377EB8', '#4DAF4A', '#E41A1C', '#984EA3']).domain(['R','D','O','U'])!#"
This is on my list of things to make easier.
Let me know if this doesn't work.
The issue with the accepted answer above is that defining an ordinal scale will not guarantee that specific colors are bound to specific categories R, D, O and U. The color mapping will change depending on the input data. To assign each color specifically you can use assignColor like this
d1$setTemplate(afterScript = '<script>
myChart.assignColor("R","#377EB8");
myChart.draw();
</script>')

ggplot2 equivalent of 'factorization or categorization' in googleVis in R

Due to static graph prepared by ggplot, we are shifting our graphs to googleVis with interactive charts. But when it comes to categorization we are facing many problems. Let me give example which will help you understand:
#dataframe
df = data.frame( x = sample(1:100), y = sample(1:100), cat = sample(c('a','b','c'), 100, replace=TRUE) )
ggplot2 provides parameter like alpha, colour, linetype, size which we can use with categories like shown below:
ggplot(df) + geom_line(aes(x = x, y = y, colour = cat))
Not just line chart, but majority of ggplot2 graphs provide categorization based on column values. Now I would like to do the same in googleVis, based on value df$cat I would like parameters to get changed or grouping of line or charts.
Note:
I have already tried dcast to make multiple columns based on category column and use those multiple columns as Y input, but that it not what I would like to do.
Can anyone help me regarding this?
Let me know if you need more information.
vrajs5 you are not alone! We struggled with this issue. In our case we wanted to fill bar charts like in ggplot. This is the solution. You need to add specifically named columns, linked to your variables, to your data table for googleVis to pick up.
In my fill example, these are called roles, but once you see my syntax you can abstract it to annotations and other cool features. Google has them all documented here (check out superheroes example!) but it was not obvious how it applied to r.
#mages has this documented on this webpage, which shows features not in demo(googleVis):
http://cran.r-project.org/web/packages/googleVis/vignettes/Using_Roles_via_googleVis.html
EXAMPLE ADDING NEW DIMENSIONS TO GOOGLEVIS CHARTS
# in this case
# How do we fill a bar chart showing bars depend on another variable?
# We wanted to show C in a different fill to other assets
suppressPackageStartupMessages(library(googleVis))
library(data.table) # You can use data frames if you don't like DT
test.dt = data.table(px = c("A","B","C"), py = c(1,4,9),
"py.style" = c('silver', 'silver', 'gold'))
# Add your modifier to your chart as a new variable e.g. py1.style
test <-gvisBarChart(test.dt,
xvar = "px",
yvar = c("py", "py.style"),
options = list(legend = 'none'))
plot(test)
We have shown py.style deterministically here, but you could code it to be dependent on your categories.
The secret is myvar.googleVis_thing_youneed linking the variable myvar to the googleVis feature.
RESULT BEFORE FILL (yvar = "py")
RESULT AFTER FILL (yvar = c("py", "py.style"))
Take a look at mages examples (code also on Github) and you will have cracked the "categorization based on column values" issue.

Resources