Zoom in and zoom out for R graph - r

I know the question was already asked, but i couldn't solve my problem.
I get a graph unreadale when i choose the text argument for my graph and when i choose the identify argument it's not better.
This is what i get whith this script :
VehiculeFunction <- function(data, gamme, absciss, ordinate, label, xlim, ylim){
my.data <- data[data$GAMME == gamme,]
ma.col = rgb(red = 0.1,blue = 1,green = 0.1, alpha = 0.2)
X <- my.data[[absciss]]
Y <- my.data[[ordinate]]
Z <- my.data[[label]]
X11()
plot(X, Y, pch=20, las = 1, col = ma.col, xlab = absciss, ylab = ordinate, xlim = xlim, ylim = ylim)
text(X, Y, labels = Z, pos=3, cex = 0.7, col = ma.col)
#identify(X, Y, labels = Z, cex = 0.7)
}
VehiculeFunction(data.vehicule, "I", "GMF.24", "Cout.24", "NITG", c(0,0.2), c(0,0.2))
I used iplot, but i couldn't add the identify and text argument...
I never used ggplot, so i don't know if it's could solve my problem.
Thank you for help.

A tool that might help with is facet_zoom from the ggforce package.
I don't have access to the data.vehicule object, so I will use the mtcars data.frame for an example of zooming in on a region of the graphic.
library(ggplot2)
library(ggforce)
library(dplyr)
mtcars2 <- mtcars %>% mutate(nm = rownames(mtcars))
ggplot(mtcars2) +
aes(x = wt, y = mpg, label = nm) +
geom_text()
last_plot() +
theme_bw() +
facet_zoom(x = dplyr::between(wt, 3, 4),
y = dplyr::between(mpg, 12, 17))

Related

R: Two graphs (boxplot and barplot) sharing one X-Axis

I am trying to match two graphs in such a way that the two graphs are located vertically above each other sharing one x Axis
I already tried to use ggplot but didn't succeed. I did not manage to rewrite the commands barplot() and plot() to ggplot() in such a way that the graphs still come out right.
I would be very grateful for any help!
That's the first plot:
plot(as.factor(DauerK_mcpM$Kulturkategorie),
DauerK_mcpM$Electivity,
ylim = c(-1,1),
ylab="Elektivitätsindex",
col = DauerK_mcpM$Farbe, xaxt = "n",
main = "Elektivität Männchen mit Dauer")
abline(h = 0, lty = 2)
x.labels <- gsub("^.*?)","",levels(as.factor(DauerK_mcpM$Kulturkategorie)))
breaks <- seq(1,length(x.labels), 1)
axis(1, labels = x.labels, at = breaks, las = 2, cex.axis = 1)
dev.off()
That's the second plot:
barplot(Dauer_pro_Kultur_prozentM,
beside = TRUE,
xaxt = "n", ylab="verbrachte Zeit [%]",
main = "Männchen", col = Dauer_pro_KulturW$Farbe)
x.labels <- gsub("^.*?)", "", levels(as.factor(Dauer_pro_KulturW$Kulturkategorie)))
length <- length(x.labels)*1.2
breaks <- seq(from = 0.7, to = length, 1.2)
axis(1, labels = x.labels, at = breaks, las = 2, cex.axis = 1)
dev.off()
This can be done in ggplot by adding an indicator column for the plot type and then faceting by that indicator:
library(tidyverse)
#create some data
set.seed(20181022)
data <- data.frame(x = letters[ceiling(runif(100, 0, 10))],
y = runif(100),
stringsAsFactors = FALSE)
#duplicate the data and add an indicator for the Plot Type
data <- data %>%
bind_rows(data) %>%
mutate(PlotType = rep(1:2, each = nrow(data)))
#Facet by the plot type and subset each geom
data %>%
ggplot(aes(x, y)) +
facet_grid(PlotType~., scales = "free")+
geom_boxplot(data = filter(data, PlotType == 1)) +
geom_bar(data = filter(data, PlotType == 2), stat = "identity")

Fail to add a linear trend line on a barplot in R

I have created a barplot using barplot and then I want to show the linear trend. I use abline but the linear trend line does not show in the figure. I wonder what the problem is. Thanks.
set.seed(100)
Mydata=rnorm(65)
Year=1950:2014
barplot(Mydata)
fit=lm(Mydata~Year)
abline(fit)
As #G5W points out, fit=lm(Mydata~I(Year-1950)). But the new problem is that the trend line is too "long". As shown in the second figure, the trend line goes beyond the barplot. Is there any advice?
If you can use ggplot:
library(ggplot2)
df <- data.frame(Mydata, Year)
ggplot(df, aes(x = Year, y = Mydata)) +
geom_bar(stat = "identity") +
geom_smooth(method = "lm")
To expand on #bouncyball's comment, use a higher value of line width (lwd) to resemble barplot if you want.
plot(Year, Mydata, type = 'h',lwd=5,col = "grey")
abline(fit, lty =2)
EDIT
First copy this function
barplot2 <- function(x, y, lty = 1, lwd = 1, col = "grey", border = "black"){
w = ((max(x) - min(x))/length(x)) * 0.75
plot(x, y, type = 'p', pch = NA, yaxt = "n", xaxt = "n", xlab = "", ylab = "")
for (i in 1:length(x)){
x1 = x[i] - w/2
x2 = x[i] + w/2
y1 = 0
y2 = y[i]
polygon(x = c(x1,x2,x2,x1), y = c(y1,y1,y2,y2), lty = lty, lwd = lwd, col = col, border = border)
}
}
Then make the barplot
barplot2(Year,Mydata)
Then add the ablineclip from plotrix library
ablineclip(fit, x1 = min(Year), x2 = max(Year), y1 = min(Mydata), y2 = max(Mydata))

Label the x axis correct in a histogram in R

I tried to name the x axis correct.
hist(InsectSprays$count, col='pink', xlab='Sprays', labels=levels(InsectSprays$spray), xaxt='n')
axis(1, at=unique(InsectSprays$spray), labels=levels(InsectSprays$spray))
But this produces
I want the letters below the bars and not on top.
You have to plot the labels at the histogram bin midpoints. If you want to remove the axis and just have lettering, the padj will move the letters closer to the axis which you just removed.
h <- hist(InsectSprays$count, plot = FALSE)
plot(h, xaxt = "n", xlab = "Insect Sprays", ylab = "Counts",
main = "", col = "pink")
axis(1, h$mids, labels = LETTERS[1:6], tick = FALSE, padj= -1.5)
I generally think barplot are more suited for categorical variables. A solution in base R could be, with some rearrangement of the data:
d <- aggregate(InsectSprays$count, by=list(spray=InsectSprays$spray), FUN=sum)
d <- d[order(d$x, decreasing = T),]
t <- d$x
names(t) <- d$spray
barplot(t, las = 1, space = 0, col = "pink", xlab = "Sprays", ylab = "Count")
The output is the following:
Since you mentioned a ggplot solution would be nice:
library(ggplot)
library(dplyr)
InsectSprays %>%
group_by(spray) %>%
summarise(count = sum(count)) %>%
ggplot(aes(reorder(spray, -count),count)) +
geom_bar(stat = "identity", fill = "pink2") +
xlab("Sprays")
The output being:

Error bars are not plotted when axes are reversed (plotCI from package plotrix)

I want to change the point of origin for a plot with vertical and horizontal error bars. I'm using the plotCI function from the 'plotrix' package for plotting.
A very short reproducible example:
x <- c(1, 2)
y <- c(3, 4)
err.x <- c(0.5, 0.2)
err.y <- c(0.25, 0.3)
plotCI(x, y, uiw = err.x, err = "x",
ylim = range(y+err.y, y-err.y))
plotCI(x, y, uiw = err.y, err = "y", add = T)
Everything is fine in this plot. I got both horizontal and vertical error bars.
plotCI(x, y, uiw = err.x, err = "x",
ylim = rev(range(y+err.y, y-err.y)))
plotCI(x, y, uiw = err.y, err = "y", add = T)
Here, I only get the horizontal error bars. It seems as if the reversal of the y-axis wasn't 'recognized' by the second call to plotCI.
Any ideas?!? Thanks a lot!
I love plotrix and its associated functions but I think what you're trying to do is hampered by the arrows() function that plotCI() relies on not honoring the ylim reversal. You can instead use ggplot2 to get the plot you want:
x <- c(1, 2)
y <- c(3, 4)
err.x <- c(0.5, 0.2)
err.y <- c(0.25, 0.3)
library(ggplot2)
ggplot(data.frame(x,y,err.x,err.y), aes(x=x, y=y)) +
geom_point() +
geom_errorbar(aes(ymin=y-err.y, ymax=y+err.y), width=0.05) +
geom_errorbarh(aes(xmin=x-err.x, xmax=x+err.x), height=0.05) +
scale_y_reverse()

R - color scatterplot points by z value with legend

I have a scatterplot and wish to color the points by a z value assigned to each point. Then I want to get the legend on the right hand side of the plot to show what colors correspond to what z values using a nice smooth color spectrum.
Here are some x,y,z values you can use so that this is a reproducible example.
x = runif(50)
y = runif(50)
z = runif(50) #determines color of the (x,y) point
I suppose the best answer would be one that is generalized for any color function, but I do anticipate using rainbow()
Translated from this previous question:
library(ggplot2)
d = data.frame(x=runif(50),y=runif(50),z=runif(50))
ggplot(data = d, mapping = aes(x = x, y = y)) + geom_point(aes(colour = z), shape = 19)
If you don't want to use ggplot2 I modified a solution to this provided by someone else, I don't remember who.
scatter_fill <- function (x, y, z,xlim=c(min(x),max(x)),ylim=c(min(y),max(y)),zlim=c(min(z),max(z)),
nlevels = 20, plot.title, plot.axes,
key.title, key.axes, asp = NA, xaxs = "i",
yaxs = "i", las = 1,
axes = TRUE, frame.plot = axes, ...)
{
mar.orig <- (par.orig <- par(c("mar", "las", "mfrow")))$mar
on.exit(par(par.orig))
w <- (3 + mar.orig[2L]) * par("csi") * 2.54
layout(matrix(c(2, 1), ncol = 2L), widths = c(1, lcm(w)))
par(las = las)
mar <- mar.orig
mar[4L] <- mar[2L]
mar[2L] <- 1
par(mar = mar)
# choose colors to interpolate
levels <- seq(zlim[1],zlim[2],length.out = nlevels)
col <- colorRampPalette(c("red","yellow","dark green"))(nlevels)
colz <- col[cut(z,nlevels)]
#
plot.new()
plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i", yaxs = "i")
rect(0, levels[-length(levels)], 1, levels[-1L],col=col,border=col)
if (missing(key.axes)) {if (axes){axis(4)}}
else key.axes
box()
if (!missing(key.title))
key.title
mar <- mar.orig
mar[4L] <- 1
par(mar = mar)
# points
plot(x,y,type = "n",xaxt='n',yaxt='n',xlab="",ylab="",xlim=xlim,ylim=ylim,bty="n")
points(x,y,col = colz,xaxt='n',yaxt='n',xlab="",ylab="",bty="n",...)
## options to make mapping more customizable
if (missing(plot.axes)) {
if (axes) {
title(main = "", xlab = "", ylab = "")
Axis(x, side = 1)
Axis(y, side = 2)
}
}
else plot.axes
if (frame.plot)
box()
if (missing(plot.title))
title(...)
else plot.title
invisible()
}
Just run the function first and it is ready to be used. It is quite handy.
# random vectors
vx <- rnorm(40,0,1)
vy <- rnorm(40,0,1)
vz <- rnorm(40,10,10)
scatter_fill(vx,vy,vz,nlevels=15,xlim=c(-1,1),ylim=c(-1,5),zlim=c(-10,10),main="TEST",pch=".",cex=8)
As you can notice, it inherits the usual plot function capabilities.
Another alternative using levelplot in package latticeExtra, with three different colour palettes.
library(latticeExtra)
levelplot(z ~ x + y, panel = panel.levelplot.points, col.regions = heat.colors(50))
levelplot(z ~ x + y, panel = panel.levelplot.points,
col.regions =colorRampPalette(brewer.pal(11,"RdYlGn"))(50))
levelplot(z ~ x + y, panel = panel.levelplot.points, col.regions = rainbow(50))

Resources