R: how to optimize the position of labeling in plot - r

Hi I guess that I have quite a rudimentary question here.
I have a plot like this
but as you could easily notice, some of the label could not be displayed (some are overlapped with the symbols, some are just out of the figure frame)
I noticed that there are some way to adjust the position of labels
text(tsne_out$Y[,1], tsne_out$Y[,2], labels=samplegrouptry, pos=1)
for example, I could specify the the value of "pos" (from 1 to 4). I guess they are good enough in most cases .But I wonder whether there are some better ways to do that.
Any suggestion, thanks!
Following the suggestion from
vas_u Through change the axis ranges as well as "pos", I could get better plot:

One way around the problem would be to enlarge the axes of the plot.
Your example approximately reproduced with dummy data:
x <- rnorm(16, mean = 0)
y <- rnorm(16, mean = 1)
# Initial scatterplot with text labels out of plot area:
plot(x, y, pch = 16)
text(x, y, labels = paste("Name", 1:16), pos = 1) # Some labels outside plot area
# Second plot with the X and Y axes gently expanded:
plot(x, y, pch = 16,
xlim = 1.1*range(x),
ylim = 1.1*range(y))
text(x, y, labels = paste("Name", 1:16), pos = 1) # Labels now fit inside!
I hope this helps.

Related

How to move the vertical color strip legend in image.plot

Using image.plot from fields in R, I need to move the vertical color legend to the right a bit in order to accommodate a second y axis on the right hand side of the plot. Here is a reproducible example of what I'm talking about:
x <- seq(0, 1, 0.1)
y <- x
n <- length(x)
z <- matrix(runif(n^2), n, n)
xyzlist <- list(x, y, z)
image.plot(x,y,z)
yaxis2 <- y^2
axis(4, at = y, labels = yaxis2)
So you see how the new axis labels crash into the legend. How to move the legend over so that it doesn't crash into the new axis labels?
You can toy around (to some extent) with the legend's size and location by using the argument smallplot of the function.
In your example, you could use the following code:
library(fields)
x <- seq(0, 1, 0.1)
y <- x
n <- length(x)
z <- matrix(runif(n^2), n, n)
xyzlist <- list(x, y, z)
yaxis2 <- y^2
### code added: left, right, bottom, top
image.plot(x,y,z, smallplot = c(.89, .94, .2, .8))
axis(4, at = y, labels = yaxis2)
This yields the following plot:
Of course, you can modify the legend further, making it smaller, shorter, etc
Please, let me know whether this is what you want.
Alternative
An alternative is to draw the plot 2 times. The first call generates a plot without the legend (because it is not well specified, and this generates an error). Then the axis is plotted (with a line adjustment, which may be different depending on the size of the plotting window). Thirdly and lastly, the legend is drawn (further to the left than in the previous plot with the error).
image.plot(x,y,z, smallplot = c(.85, .86, 1, .8))
axis(4, at = y, labels = yaxis2, line = -6)
image.plot(x,y,z, smallplot = c(.89, .92, .2, .8), legend.only = TRUE)

R horizontal barplot with axis labels split between two axis

I have a horizontal barplot, with zero in the middle of the x-axis and would like the name for each bar to appear on the same side as the bar itself. The code I am using is:
abun<-data$av.slope
species<-data$Species
cols <- c("blue", "red")[(abun > 0)+1]
barplot(abun, main="Predicted change in abundance", horiz=TRUE,
xlim=c(-0.04,0.08), col=cols, names.arg=species, las=1, cex.names=0.6)
I have tried creating two separate axes and the names do appear on the desired side for each bar, but are not level with the appropriate bar. I will try and upload an image of the barplot, am still very new to R, apologies if I am missing something basic!
barplot1- names in correct position but all on one axis
barplot2- names on both sides of plot but not in line with appropriate bar
We can accomplish this using mtext:
generate data
Since you didn't include your data in the question I generated my own dummy data set. If you post a dput of your data, we could adapt this solution to your data.
set.seed(123)
df1 <- data.frame(x = rnorm(20),
y = LETTERS[1:20])
df1$colour <- ifelse(df1$x < 0, 'blue', 'red')
make plot
bp <- barplot(df1$x, col = df1$colour, horiz = T)
mtext(side = ifelse(df1$x < 0, 2, 4),
text = df1$y,
las = 1,
at = bp,
line = 1)

R - How to set the range of the colorscale in a hexbin plot

I am making a scatter plot matrix using hexbin plots to show the density of certain areas.
Example:
library(lattice)
library(hexbin)
splom(cbind(rnorm(10000),rnorm(10000),rnorm(100),rnorm(100)),
,varnames = c("A","B","C","D")
,panel = panel.hexbinplot
,lower.panel = function(x, y, ...) {
panel.fill(col = brewer.pal(9, "Greys")[ round(cor(x, y,method = "spearman") * 4 + 2)])
cpl <- current.panel.limits()
panel.text(mean(cpl$xlim), mean(cpl$ylim), round(cor(x, y,method = "spearman"),2), font=2)
}
,upper.panel = function(x, y, ...){
panel.hexbinplot(x, y, type = "r", xbins = 10, ...)
}
,pscale=0, varname.cex=1, xlab = ""
)
It seems to me, that the colorscale, i.e. which count applies to which color, is recalculated in each of the 6 hexbin plots. It doesn't make a difference here but it does in my data. How can I set all these to ONE scale, meaning that a hexagon with 25 counts has the same color in all 6 plots, no matter if the maximum count in the plot is 25 or 150.
Thanks a lot in advance.
Maybe too late, but if somebody else is having the same question...Try using the argument maxcnt, it worked for me using the package Opeanair. I generated 4 plots and every one has the same color ramp: the hexagons with the same number of counts have the same color.

R barplot straight horizontal line

My code is below
data <-read.csv("Results_15Jan2015.csv")
PartNo <- data$PartNo
TotalTime <- data$TOTAL_TIME
mp <- barplot(height = TotalTime, main = "Plot of Total Time for different Part Numbers", xlab = "Different Part Numbers", ylab = "Total Time (sec)", xlim = c(1,42), ylim = c(0,max(TotalTime)+30),
col = rainbow(nrow(data)))
text(mp, par("usr")[3], labels = PartNo, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=.9)
abline(h=mean(TotalTime))
specify_decimal <- function(x, k) format(round(x, k), nsmall=k)
text(7.5,mean(TotalTime)+25, paste("Average =",specify_decimal(mean(TotalTime),3)))
2 Questions:
a) Why is my horizontal line not drawn all the way to the right of the plot? How to draw the horizontal line all the way to the right?
b) I have a total of 42 observations, see http://imgur.com/97qHaUq
but the total number of bars shown is only 37, why? See http://imgur.com/dGj3WOt
I need to display all 42 bars in a single plot. how do I do that? thanks
As MrGrumble said, dropping the xlim argument should solve both of your problems (the line and missing bars). It might not be straightforward what this argument does in barplot function, as you don't give x explicitly. See in this example:
x <-seq(15)
barplot(x,xlim=c(1,15))
abline(h=6)
Gives a graphic with issues similar to those you are having, whereas
x <-seq(15)
barplot(x)
abline(h=6)
Behaves "as expected"

Change y-axis side when plotting factors

I have the following plot
k.factor<-factor(sample(1:5, 100, replace = T))
s.factor<-factor(sample(c("A", "B", "C"), 100, replace = T))
plot(k.factor, s.factor)
I would like to remove the left y-axis (A, B, C) and plot this information as a legend. How can I suppress this yaxis? I would also like the probability axis to be displayed as the left y axis (instead of right y axis as it is now)? How can I flip this?
Please base R answers only
If you don't mind using ggplot2 you could do it like this:
library(ggplot2)
ggplot(data.frame(k.factor, s.factor), aes(x = k.factor, fill = s.factor)) +
geom_bar(position="fill")
You can set axes=FALSE in your plotting statement and then manually add the axes using ?axis:
plot(k.factor, s.factor, axes=FALSE)
axis(1)
axis(2)
EDIT: In fact, you have to customize the axis statement.
# create offset and at variables
off <- 0.02
xat <- c(0, cumsum(prop.table(table(k.factor)) + off))
# plot
plot(k.factor, s.factor)
plot(k.factor, s.factor, axes=FALSE, off=100*off)
axis(1, at = (xat[-length(xat)] + xat[-1] - off)/2,
labels = 1:5, tick = FALSE)
axis(2)
You can also look at ?spineplot for more information about the argument off.

Resources