R - barplot | How to control space and width of bars - r

I want the bars to be close to each other, but not adjacent (beside=FALSE), and I want also the bars to be slightly thin. I have played around with space and width but I am not getting my desired results.
I prefer to stay with barplot function instead of using ggplots, but if there is no way thought it, that is ok.
This is the expected barplot (edited manually from the obtained):
And this is the obtained:
Code Used:
jpeg("03.Annotation.Distribution.DMRs.All.jpeg")
bp1 = barplot(ann[,1:2], ylim=c(0,1.1), col=ann[,3], beside=FALSE, space=10,
names.arg=c("Genome","DMRs"), las=3, xlab="Group", ylab="Frequency",
main="Annotation distribution on DMRs")
legend("top",legend=rownames(ann)[7:1], fill=ann[7:1,3], bty="n", horiz=FALSE)
dev.off()
Thankyou!

The width of the bars has to do with the size of the device you're using. You can hack the spacing by setting up a new plot window based on your data and add to it, ie, make the xlim larger than you need.
jpeg('./tmp.jpg', width = 250, height = 480, bg = 'grey90')
plot.new()
plot.window(c(0,6), c(0,1))
with(mtcars,
barplot(prop.table(table(gear, vs), 2), col = 1:3, add = TRUE,
legend.text = unique(gear), xlab = 'vs'))
dev.off()

Related

How to change width for bar chart that display only 2 items?

I wanted display 2 items on a bar chart. I have used the width argument to reduce the width of each bar but they still do not get adjusted. I found that by increasing the space argument the bars will get smaller, but they will be very far apart. Could anyone please help explain to me how to fix this problem? I have attached the codes and chart below for your reference. Thank you for your time.
predErr<-c(mars = MARS_Predictions_Err, svm = SVM_Predictions_Err)
barplot(predErr, main = "Prediction Error Bar Chart", xlab = "Models", ylab = "Err", width = 1, ylim = c(0,1000))
You have to play around with three parameters: width (sets the width of each bar), xlim (sets the range of the x-axis) and space (sets the distance between bars as a fraction of the average bar width).
For example, this parameter combination:
heights = c("m1"=2, "m2"=4)
barplot(heights,
xlab = "Models",
ylab = "Err",
width = c(0.1,0.1), xlim = c(0,1), space = 3)
gave me this result, which I believe is what you want:
I generated some data. To change the distance between the bars, I used space=1 . Is this your response to your question?
set.seed(100)
MARS_Predictions_Err<-rnorm(1,200)
SVM_Predictions_Err<-rnorm(1,200)
predErr<-c(mars = MARS_Predictions_Err, svm = SVM_Predictions_Err)
barplot(predErr, main = "Prediction Error Bar Chart",
xlab = "Models",
ylab = "Err", width = 3,
ylim = c(0,1000),
space=1)
space=1
space=0

How to change the y-axis label horizontal

I am trying to change the y-axis to being horizontal so that it can be read easier for my talk. I am new to R and don't have a lot of experience with it.
This is my code:
first.value = pt(500, 1.127344, 1.561328)
space = (1 - first.value)/648
edges = seq(first.value + space, 1 - space, space)
value.edges = 1.561328*qt(edges, 1.127344)
data = read.table(file.choose())
observed = log(data$V1)
expected = log(value.edges)
plot(observed,expected, xlim =c(4,15), ylim = c(0,14), las =1)
abline(0,1)
I would like the word expected the same orientation as observed. Thank you!
Try this,
par(mar = c(6,6,6,3))
plot(1, las=1, ylab="")
mtext(text="Test", side=2, line=4, las=1)
You can change the values in par to your liking, put your data instead of the 1 in plot, add your x labels etc... Then use mtext to write the yaxis label

Legends overlapping the plots in Rstudio

I am trying to plot an image and then overlay a legend on its top. The legend is covering the plot and I am not able to adjust it using different parameters like cex, lty, etc.
plot(cov16_2ms04h$unqC_Sp, cov16_2ms04h$unqC_My, log="xy",
col=(cov16_2ms04h$binom_q<0.001)+1,
ylab="Haplotype B Count", xlab="Haplotype A Count")
abline(0,1,col="grey")
legend("topleft",c("No significant imbalance","Significant imbalance"),pch=c(10,10),col=c(1,2), cex = 0.5)
is giving me plot as:
But, I want something like:
Thanks,
have you tried enlarge the size of the plot before overlying a legend? I tried you legend code, the legend was perfect on the plot.
The problem is with R-studio because the size of the output plot is determined by the costumized size of the pane.
To plot the results directly to a pdf or a png file the following can be done.
# plotting directly on pdf or png - select the required one
pdf("my_plot.pdf", height=6, width=6)
png("my_plot.png", width = 4, height = 4,
units = 'in', res = 300)
plot(cov16_2ms04h$unqC_Sp, cov16_2ms04h$unqC_My, log="xy",
col=(cov16_2ms04h$binom_q<0.001)+1,
ylab="Haplotype B Count", xlab="Haplotype A Count")
abline(0,1,col="grey") # draw abline
legend("topleft",c("No significant imbalance","Significant imbalance"),
pch=c(1,1),col=c(1,2), cex = 0.75) # add legend
dev.off() # close the plot
The output then comes as:
Thanks,

R: how to remove this tiny axis margin in plot

I want to get rid the small margin close to zero on X and Y value (red line on pic), and plot ONLY what is showed in red square.
I tried setting par(mar = rep(0, 4) and xlim=c(0, ...), ylim=c(0, ...) but R still keeps adding this tiny margin. How to get rid of it?
EDIT:
another point of view on my problem:
after running:
require(plotrix)
axisRange <- c(0,500)
plot(NULL, xlim = axisRange, ylim=axisRange)
draw.circle(0, 0, 200, col = "white", border = "red")
I end up with a circle positioned not in "true" 0,0 point:
EDIT2:
Actually what I want to do, is to plot circles of different radius, and save it as an image. That is why I care about the margins.
I end up with something like this (spots on the corners are for the reference):
And should be more like this:
You can set the xaxs and yaxs arguments to "i" as opposed to the default of "r". From the par help page:
Style "r" (regular) first extends the data range by 4 percent at each
end and then finds an axis with pretty labels that fits within the
extended range.
Style "i" (internal) just finds an axis with pretty labels that fits
within the original data range.
library(plotrix)
axisRange <- c(0,500)
par(mar = rep(0,4))
plot(NULL, xlim = axisRange, ylim=axisRange, xaxs = "i", yaxs = "i")
draw.circle(0, 0, 200, col = "white", border = "red")
Gives:

How reduce the size of the legend to fit in the figure or shift it to the top left?

I am trying to draw a bar plot but the legend is on the top right and it is shadowed by the bar plots. How shall I move the legend to the topleft or reduce its size to fit it properly in the right top side. Below is the code and the picture.
M<-read.delim("~/Desktop/sample.txt",row.names="Methods")
M<-as.matrix(M)
barplot(M, main="Obs by different methods at different replicates",
xlab="Number of observations", col=c("darkblue","red","green","yellow"),ylab="Number of stages",
legend = rownames(M), beside=TRUE)
How shall I change the code to fit it properly ?
barplot() adds a legend by calling the legend() function, which is extremely flexible and allows you to specify exactly where a legend should be drawn by providing either x and y coordinates or a descriptive keyword (check out ?legend for details).
You can call legend() directly:
barplot(VADeaths, beside = TRUE, ylim = c(0, 100), col = 1:5)
legend("topleft", legend = rownames(VADeaths), fill = 1:5)
Or pass arguments to legend() via barplot():
barplot(VADeaths, beside = TRUE, ylim = c(0, 100),
legend.text = rownames(VADeaths),
args.legend = list(x = "topleft"))
Use a specific call to the legend() function to move it to the 'topleft' corner. For example:
M<-read.delim("~/Desktop/sample.txt",row.names="Methods")
M<-as.matrix(M)
barplot(M, main="Obs by different methods at different replicates",
xlab="Number of observations", col=c("darkblue","red","green","yellow"),ylab="Number of stages", beside=TRUE)
legend('topleft', rownames(M), fill=c("darkblue","red","green","yellow"))
Does this help?
Otherwise, you can also play with other parameters of the legend, for example putting a cex= inside its call. I will let you discover them by typing ?legend in the R console.

Resources