rCharts nvd3 library force ticks - r

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.

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

How to fit logarithmic curve over the points in r?

I want to fit my points with logarithmic curve. Here is my data which contains x and y. I desire to plot x and y and the add a logarithmic fitting curve.
x<-structure(list(X2.y = c(39.99724745, 29.55541525, 23.39578201,
15.46797044, 10.52063652, 7.296161198, 6.232038434, 4.811851132,
4.641281547, 4.198523289, 3.325515839, 2.596563723, 1.894902523,
1.556380314), X5.y = c(62.76037622, 48.54726084, 37.71302646,
24.93942365, 17.71060023, 13.31130267, 10.36341862, 7.706914722,
7.170517624, 6.294292013, 4.917428837, 3.767836298, 2.891519878,
2.280974128), X10.y = c(77.83154815, 61.12151516, 47.19228808,
31.21034981, 22.47098182, 17.29384973, 13.09875178, 9.623698726,
8.845091983, 7.681873268, 5.971413758, 4.543320659, 3.551367285,
2.760718282), X25.y = c(96.87401383, 77.00911883, 59.16936025,
39.13368164, 28.48573658, 22.32580849, 16.55485248, 12.0455604,
10.96092113, 9.435085861, 7.303126501, 5.523147205, 4.385086234,
3.366876291), X50.y = c(111.0008027, 88.79545082, 68.05463659,
45.01166182, 32.94782526, 26.05880295, 19.11878542, 13.84223574,
12.53056405, 10.73571912, 8.291067088, 6.25003851, 5.003586577,
3.81655893), X100.y = c(125.0232816, 100.4947544, 76.87430545,
50.84623991, 37.37696657, 29.76423356, 21.66378667, 15.6256447,
14.08861698, 12.0267487, 9.271712877, 6.971562563, 5.61752001,
4.262921183)), class = "data.frame", row.names = c(NA, -14L))
I tried this:
single_idf<-function(x) {
idf<-x
durations = c(5/60, 10/60, 15/60, 30/60, 1, 2, 3, 4, 5, 6, 8, 12, 18, 24)
nd = length(durations)
Tp = c(2, 5, 10, 25, 50, 100)
nTp = length(Tp)
psym = seq(1, nTp)
# open new window for this graph, set plotting parameters for a single graph panel
windows()
par(mfrow = c(1,1), mar = c(5, 5, 5, 5), cex = 1)
# set up custom axis labels and grid line locations
ytick = c(1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,
200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400)
yticklab = as.character(ytick)
xgrid = c(5,6,7,8,9,10,15,20,30,40,50,60,120,180,240,300,360,
420,480,540,600,660,720,840,960,1080,1200,1320,1440)
xtick = c(5,10,15,20,30,60,120,180,240,300,360,480,720,1080,1440)
xticklab = c("5","10","15","20","30","60","2","3","4","5","6","8","12","18","24")
ymax1 = max(idf)
durations = durations*60
plot(durations, col=c("#FF00FF") ,lwd=c(1), idf[, 1],
xaxt="n",yaxt="n",
pch = psym[1], log = "xy",
xlim = c(4, 24*60), ylim = range(c(1,idf+150)),
xlab = "(min) Duration (hr)",
ylab = "Intensity (mm/hr)"
)
for (iT in 2:nTp) {
points(durations, idf[, iT], pch = psym[iT], col="#FF00FF",lwd=1)
}
for (iT in 1:nTp) {
mod.lm = lm(log10(idf[, iT]) ~ log10(durations))
b0 = mod.lm$coef[1]
b1 = mod.lm$coef[2]
yfit = log(10^(b0 + b1*log10(durations)))
lines(durations,col=c("#FF00FF"),yfit, lty = psym[iT],lwd=1)
}
}
But when I run this, the curves stands far away from the points. I want to see curves over the points. How can I arrange this?
single_idf(x)
Consider this as an option for you using ggplot2 and dplyr. Also added method='lm' to match OP expected output (Many thanks and credits to #AllanCameron for his magnificent advice):
library(ggplot2)
library(dplyr)
#Data
df <- data.frame(x,y)
#Plot
df %>%
pivot_longer(-y) %>%
ggplot(aes(x=log(y),y=log(value),color=name,group=name))+
geom_point()+
stat_smooth(geom = 'line',method = 'lm')
Output:
The main problem is that you were plotting the natural log of the fit rather than the fit itself.
If you change the line
yfit = log(10^(b0 + b1*log10(durations)))
To
yfit = 10^(b0 + b1*log10(durations))
And rerun your code, you get

R ggplot2 gave accent in legend

I created a function to plot some data per city in a line graph. I want the user to be able to change the label of each city in the legend.
A simplified example:
example_plot <- function(plot_labs = c("Anvers", "Liège")){
graphics.off()
input <- data.table(x_axis = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
y_axis = c(5, 6, 4, 2, 8, 9, 3, 1, 7, 5),
City = c("Anvers", "Anvers", "Anvers", "Anvers", "Anvers",
"Liege", "Liege", "Liege", "Liege", "Liege"))
ggplot(data = input, aes(x = x_axis, y = y_axis, group = City, lty = City)) +
geom_line() + scale_linetype_manual(labels = plot_labs, breaks = c("Anvers",
"Liege"), values = 1:2)
}
My problem:
When I save the function as "example_plot.R" and then call it in the command prompt with no argument, the accent in "Liège" does not display correctly:
example_plot()
If I call the function with the plot_labs argument, it displays correctly:
example_plot(plot_labs = c("Anvers", "Liège"))
What I find even stranger is that if I copy-paste the function's code in the command prompt (instead of 'source(example_plot.R")'), then everything works fine.
Any idea why it behaves differently when the function is saved?
You're probably saving your source file in an encoding such as UTF-8 and then reopen or source it assuming it's in Latin-1.
If you're using RStudio, check the menu points File/Save with encoding, and File/reopen with encoding, and ensure the character encodings match.

turn off grid lines for R xyplot timeseries

I am plotting a time series with the timePlot function of the open air package of R. The graph has grey grid lines in the background that I would like to turn off but I do not find a way to do it. I would expect something simple such as grid = FALSE, but that is not the case. It appears to be rather complex, requiring the use of extra arguments which are passed to xyplot of the library lattice. I believe the answer lies some where in the par.settings function but all attempts have failed. Does anyone have any suggestions to this issue?
Here is by script:
timeozone <- import(i, date="date", date.format = "%m/%d/%Y", header=TRUE, na.strings="")
ROMO = timePlot(timeozone, pollutant = c("C7", "C9", "C10"), group = TRUE, stack = FALSE,y.relation = "same", date.breaks = 9, lty = c(1,2,3), lwd = c(2, 3, 3), fontsize = 15, cols = c("black", "black"), ylab = "Ozone (ppbv)")
panel = function(x, y) {
panel.grid(h = 0, v = 0)
panel.xyplot(x,y)
}

Plotting with Vennerable package in R

Here is a very basic example:
library(vennerable)
srl.venn <- Venn(SetNames=c("Cognitive condition","Operations","Individual differences"),
Weight=c(0,30, 21, 15, 1, 8, 3, 6))
plot(srl.venn)
All I'm trying to do is to remove borders around circles, and format colors and fonts. However, still haven't done much.
Could you please share any useful examples?
Check out VennThemes for changing parameters within the plot. For example:
library(Vennerable)
srl.venn <- Venn(SetNames=c("Cognitive condition","Operations","Individual differences"),
Weight=c(0,30, 21, 15, 1, 8, 3, 6))
srl.venn.c <- compute.Venn(srl.venn, doWeights=T)
gp <- VennThemes(srl.venn.c, colourAlgorithm = "binary")
plot(srl.venn.c, gpList = gp, show = list(FaceText = "signature", SetLabels = FALSE,
Faces = FALSE, DarkMatter = FALSE))
More detail can be found in the man pages or by calling vignette("Venn")

Resources