I have an R dataframe and some scatterplots and barplots created from them.
df <- data.frame(var1 = c(2,3,8,2,5,6,2,7,4,4),var2 = runif(n = 10),var3 = runif(n=10,min = 10,max=50),var4 = c(rep("A",5),rep("B",5)))
plot(df$var1,df$var2)
plot(df$var2,df$var3)
barplot(df$var3,names.arg=df$var4)
If I am interested in a point on the first plot, I would like to identify that point on the second, third or multiple other plots. I would like to be able to do this interactively (for example using mouse-over hover effects) in a shareable rmarkdown document.
How can one go about doing this in R either using base graphics, ggplot or even something like shiny/rCharts? Any examples/links would be appreciated. Thanks.
You can use the identify function to locate the points in a scatterplot interactively in base R.
As an example, you can identify the pairs of variables in the second plot with
identify(df$var2,df$var3)
Once you have clicked on the point of interest, hit the Esc key. The row number corresponding to the point on which you clicked will be displayed in the console and on the graph.
In this case I have clicked on a point near var2=0.5 and var3=30. The result shows that this is point number 2 in the dataset.
> identify(df$var2,df$var3) # Hit Esc key once you have selected the point.
[1] 2 # <- this is the result: the index (row) number of the selected point
#> df[2,]
# var1 var2 var3 var4
#2 3 0.481937 29.54026 A
For more information see ?identify
Related
I'm completely new to R, and I have been tasked with making a script to plot the protocols used by a simulated network of users into a histogram by a) identifying the protocols they use and b) splitting everything into a 5-second interval and generate a graph for each different protocol used.
Currently we have
data$bucket <- cut(as.numeric(format(data$DateTime, "%H%M")),
c(0,600, 2000, 2359),
labels=c("00:00-06:00", "06:00-20:00", "20:00-23:59")) #Split date into dates that are needed to be
to split the codes into 3-zones for another function.
What should the code be changed to for 5 second intervals?
Sorry if the question isn't very clear, and thank you
The histogram function hist() can aggregate and/or plot all by itself, so you really don't need cut().
Let's create 1,000 random time stamps across one hour:
set.seed(1)
foo <- as.POSIXct("2014-12-17 00:00:00")+runif(1000)*60*60
(Look at ?POSIXct on how R treats POSIX time objects. In particular, note that "+" assumes you want to add seconds, which is why I am multiplying by 60^2.)
Next, define the breakpoints in 5 second intervals:
breaks <- seq(as.POSIXct("2014-12-17 00:00:00"),
as.POSIXct("2014-12-17 01:00:00"),by="5 sec")
(This time, look at ?seq.POSIXt.)
Now we can plot the histogram. Note how we assign the output of hist() to an object bar:
bar <- hist(foo,breaks)
(If you don't want the plot, but only the bucket counts, use plot=FALSE.)
?hist tells you that hist() (invisibly) returns the counts per bucket. We can look at this by accessing the counts slot of bar:
bar$counts
[1] 1 2 0 1 0 1 1 2 3 3 0 ...
I have a dataframe "df" that has 120 rows and 2 columns containing numbers as shown...
V1 V2
10001 177417
227418 267719
317720 471368
I want to be able to lay these along the X-axis of a plot with a line connecting the values from V1 t0 V2 in each row.
one option would be to use seq(V1,V2) for each row then concatenate to create a full series, However with the the amount of data involved, the object size runs to >10GB and is therefore not a viable option. The Y-axis position here is not important.
Any ideas?
First create a plot object, then enter the rest of the rows using the segments function:
plot(x=c(1,1), y=df[1,], xlim = c(1,nrow(df)), ylim=range(df), type='l')
segments(x0=2:nrow(df), x1=2:nrow(df), y0=df[-1,1], y1=df[-1,2])
Here is how it looks on a random cumulative set:
df <- apply(as.data.frame(cbind(rnorm(1000),rnorm(1000))),2,cumsum)
How can I plot 7 different graphs on one pdf page on R?
I currently use matplot, which doesn't seem to have this option. I need to plot columns of data against columns of data.
I initially tried to do this with the lattice library, but I can't seem to figure out how to plot the columns of data. It seems to want a function.
To create a pdf of plots, you can do something like this. To initialize a pdf document use the pdf function with a file name first. dev.off() at the end will close the graphics device and complete the pdf. Afterwards, you should see a new document in the working directory (in this example - 'plots.pdf').
d <- data.frame(matrix(sample(c(1:700), 2000, TRUE), 10, 20))
pdf('plots')
par(mfrow = c(3, 3)) ## set the layout to be 3 by 3
sapply(1:9, function(i) plot(d[,i]))
dev.off()
Which produces this pdf
If you want to do this with base graphics, I strongly recommend using the layout() function. It takes a matrix which defines how to split up the window. It will make a row for every row in your matrix and a column for every column. It draws the plots in order of the number of the cells. So if you pass the matrix
#layout(matrix(c(1:7,7), ncol=2, byrow=T))
# [,1] [,2]
#[1,] 1 2
#[2,] 3 4
#[3,] 5 6
#[4,] 7 7
the first plot will go in the upper left, the second in the upper right, etc, until the 7th plot goes all the way at the bottom. You could just have it take up only the bottom left if you like by specifying a different number in the bottom right.
To reset the layout back to "normal" just call
layout(1)
you could then create a for loop to make each plot.
If you want one plot to do all pairwise comparisons, the pairs() plotting function might be what you want
dd<-matrix(runif(5*5), ncol=5)
pairs(dd)
or the lattice equivalent is splom()
i would like to write a function with graphical output of original data regression and one for modified data. The original data regression should be an option. Moreover there should be legends in the graphs. And here is my problem:
If i choose the option: orig.plot=FALSE, everything works ok.
But when i choose the other option: orig.plot=TRUE, the position of my legends is not very satisfying.
# Generation of the data set
set.seed(444)
nr.outlier<- 10
x<-seq(0,60,length=150);
y<-rnorm(150,0,10);
yy<-x+y;
d<-cbind(x,yy)
# Manipulation of data:
ss1<-sample(1:nr.outlier,1) # sample size 1
sri1<-sample(c(1:round(0.2*length(x))),ss1) # sample row index 1
sb1<-c(yy[quantile(yy,0.95)<yy])# sample base 1
d[sri1,2]<-sample(sb1,ss1,replace=T) # manipulation of part 1
ss2<-nr.outlier-ss1 # sample size 2
sri2<-sample(c(round(0.8*length(x)+1):length(x)),ss2) # sample row index 2
sb2<-c(yy[quantile(yy,0.05)>yy])# sample base 2
d[sri2,2]<-sample(sb2,ss2,replace=T) # manipulation of par 2
tlm2<-function(x,y,alpha=0.95,orig.plot=FALSE,orig.ret=FALSE){
m1<-lm(y~x)
res<-abs(m1$res)
topres<-sort(res,decreasing=TRUE)[1:round((1-alpha)*length(x))] # top alpha*n residuals
topind<-rownames(as.data.frame(topres)) # indices of the top residuals
x2<-x[-as.numeric(topind)] #
y2<-y[-as.numeric(topind)] # removal of the identified observations
m2<-lm(y2~x2)
r2_m1<-summary(m1)$'r.squared'
r2_m2<-summary(m2)$'r.squared'
if(orig.plot==TRUE){
par(mfrow=c(2,1))
plot(x,y,xlim=range(x),ylim=c(min(d[,2])-30,max(d[,2]+30)),main="Model based on original data")
abline(m1$coef);legend("topleft",legend=bquote(italic(R)^2==.(r2_m1)),bty="n")
}
plot(x2,y2,xlim=range(x),ylim=c(min(d[,2])-30,max(d[,2]+30)),main="Model based on trimmed data")
abline(m2$coef);
legend("topleft",legend=bquote(atop(italic(R)^2==.(r2_m2),alpha==.(alpha))),bty="n")
return(if(orig.ret==TRUE){list(m1=m1,m2=m2)} else{m2})
}
tlm2(d[,1],d[,2])
tlm2(d[,1],d[,2],orig.plot=T)
Can anyone give me a hint?
Thank You in advance!
The problem is that atop is essentially a division (i.e. x/y) without plotting the division bar. It also centers the denominator. The solution is to use expression instead of bquote. However, to mix expressions and variables, you need to use substitute and eval:
Here's what your legend call should look like:
legend("topleft",legend=c(eval(substitute(expression(italic(R)^2==my.r2), list(my.r2 = r2_m2))) ,
eval(substitute(expression(alpha==my.alpha), list(my.alpha = alpha)))
)
,bty="n")
And here's the result:
Given a data frame with a column that contains strings. I would like to plot the frequency of strings that bear a certain pattern. For example
strings <- c("abcd","defd","hfjfjcd","kgjgcdjrye","yryriiir","twtettecd")
df <- as.data.frame(strings)
df
strings
1 abcd
2 defd
3 hfjfjcd
4 kgjgcdjrye
5 yryriiir
6 twtettec
I would like to plot the frequency of the strings that contain the pattern `"cd"
Anyone with a quick solution?
I presume from your question that you meant to have some entries that appear more than once, so I've added one duplicate string:
x <- c("abcd","abcd","defd","hfjfjcd","kgjgcdjrye","yryriiir","twtettecd")
To find only those strings that contain a specific pattern, use grep or grepl:
y <- x[grepl("cd", x)]
To get a table of frequencies, you can use table
table(y)
y
abcd hfjfjcd kgjgcdjrye twtettecd
2 1 1 1
And you can plot it using plot or barplot as follows:
barplot(table(y))
Others have already mentioned grepl. Here is an implementation with plot.density using grep to get the positions of the matches
plot( density(0+grepl("cd", strings)) )
If you don't like the extension of the density plot beyond the range there are other methods in the 'logspline' package that allow one to get sharp border at range extremes. Searching RSiteSearch
check "Kernlab" package.
You can define a kernel (pattern) which could any kind of string and count them later on.