I want to have two plots next to each other and a common legend for both.
Like This:
Plot 1 | Plot 2 | Legend
Unfortunately, the legend is plotted inside of the second plot...
This is my current approach:
par(mfrow=c(1,3))
plot(...)
plot.new()
plot(...)
legend("center", ...)
I thought with par(mfrow=c(1,3)) I would get one row with 3 columns of plots - so exactely the result I wanted to obtain.
Is the legend maybe not treated as a plot but as belonging to plot number 2 and so it is plotted with the same column?
You were close. legend needs a plot.new in front of it, if you want to have it as a "standalone" plot.
par(mfrow=c(1, 3))
plot(1:10)
plot(1:10)
plot.new()
legend("center", pch=1, legend=c("x", "y"))
Result
I hope this works for you as an example. Nevertheless, there are better libraries to be used such as ggplot2 or plotly.
par(mfrow = c(1, 2), oma = c(0, 0, 0, 2))
plot(hp~mpg, data=mtcars, col=cyl,pch=19)
plot(disp~wt, data=mtcars, col=cyl,pch=19)
legend(x=6, y=250, legend=as.numeric(levels(factor(mtcars$cyl))), pch=19, col= as.numeric(levels(factor(mtcars$cyl))) )
Related
I would like to increase the font size of axis annotations in a hexbinplot.
library(hexbin)
df <- data.frame(x=rnorm(1000),y=rnorm(1000))
hb <- hexbin(x=df$x, df$y)
myPlot <- plot(hb, xlab="", ylab="", legend=FALSE)
I would like the -3, ..., 2 and the -2, ..., 3 on the axes to be larger.
This earlier thread already helped me with axis labels, but the suggestion about how to change the annotations ("use grid.ls()" - how?) is a little too cryptic for me. I am more fluent in base graphics than in lattice.
Try this.
library(grid)
myPlot <- plot(hb, xlab="", ylab="", legend=FALSE)
grid.ls()
# GRID.rect.250
# GRID.xaxis.251
# GRID.yaxis.252
# GRID.polygon.253
grid.edit("GRID.xaxis.251", gp=gpar(fontsize=20))
grid.edit("GRID.yaxis.252", gp=gpar(fontsize=20))
The grid.ls() function shows the parts of the graph. The axis labels are GRID.xaxis.251 and GRID.yaxis.252. The name labels should be the same but the numbers will be different so you will have to modify the grid.edit() lines to match the output from grid.ls().
I want to have the plot legend for a pie chart as a single plot (6 graphics at a page - 5 plots, 1 legend). Now I have difficulties adjusting the space between the 2 columns.
I used the following code (by try and error):
#Colors
colors=c("blue","green","yellow","orange","red","purple","pink","grey")
legtext <- c("G","G*E","E","Source","Source*E",
"Table*E","Table*Block*E","Residual Error")
#Code for chart
pie3D(#data for pie
rooting1,
#specify labels vector
#labels=labels,
#specify labels size
labelcex=0.9,
#how much different pies go from each other
explode=0.1,
#height of chart
height=0.1,
#Main title
theta=pi/3,
#Colors
col=colors
)
#Code for legend
xcoords <- c(0.9,1,1.1,1.2)
secondvector <- (1:length(legtext))-1
textwidths <- xcoords/secondvector # this works for all but the first element
textwidths[1] <- 0
legend(-1, 0.9,ncol=2,
c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"),
cex = 0.8,
fill = colors,
text.width=textwidths)
The plot I get is this: I want to remove the vertical lines and if possible, remove the rest of the chart as I only want to display the legend.
Legend I get:
Can anybody help me?
Add bty="n" to your legend:
legend(-1, 0.9,ncol=2,
c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"),
cex = 0.8,
fill = colors,
text.width=textwidths,
bty="n")
As for the other question - how to get rid of the chart itself, this will take some fiddling. Basically, what you can do is to make an empty chart, but adjusting the xlim and ylim, as well as margins so that there is enough room for the legend:
par(mar=c(0.1,0.1,0.1,0.1)) # you don't need large margins
# but maybe you need more than 0.1
plot(NA, xlim=c(-1,1), ylim=c(-1,1), axes=FALSE, xlab="", ylab="")
# this makes an empty plot
# you may need to change xlim and ylim (or the x and y of your legend)
# ... so that the legend would start from the left/upper corner
I am a beginner with R. I managed to plot my data into overlapping histograms. However, I would like to place all the histograms on one page. I am struggling as I am not able to tell R, which sets to pick (only manage to plot one of the plots).
This is the code:
df<-read.csv("Salt dshalo sizes.csv",header=T)
#View(df)
library(ggplot2)
DSA<-df[,1]
DS1<-df[,2]
DSB<-df[,5]
DS2<-df[,6]
DSC<-df[,9]
DS3<-df[,10]
#remove the NA column by columns separately or it will chop the data
DSA=na.omit(DSA)
DS1=na.omit(DS1)
DSB=na.omit(DSB)
DS2=na.omit(DS2)
DSC=na.omit(DSC)
DS3=na.omit(DS3)
#plot histograms for DSA, DSB and DSC on one same graph
hist(DSA, prob=TRUE, main="Controls", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
hist(DSB, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
hist(DSC, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
#add a legend to the histogram
legend("topright", c("Control 1", "Control2", "Control3"), text.width=c(1,1,1),lwd=c(2,2,2),
col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
box()
#plot histograms for DS1, DS2 and DS3 on one same graph
hist(DS1, prob=TRUE, main="Monoculture Stressed", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
hist(DS2, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
hist(DS3, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
#add a legend to the histogram
legend("topright", c("DS1", "DS2", "DS3"), text.width=c(1,1,1),lwd=c(2,2,2),
col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
box()
# put both overlapping histograms onto one page
combined <- par(mfrow=c(1, 2))
plot(hist(DSA),main="Controls")
plot(hist(DS1),main="Monoculture stressed")
par(combined)
Basically, I get two separate overlapping histograms, but cannot put them on the same page.
EDIT: I evidently didn't read your question thoroughly. I see you figured out the add =T.
I assume what you are looking for then is the comment I made first:
par(mfrow = c(a,b)) where a and b are the number of rows and columns you want the graphics objects to be printed. I used c(2,2) for this pic.
I made a comment, but sounds like you may be talking about the add=T option.
a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col="yellow")
hist(b, add=T, col="purple" )
you can play around with transparency options on colors to see both overlap. Such as rgb(1,0,0,1/4) as the color.
With transparency colors:
a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col=rgb(1,1,0,1/4))
hist(b, add=T, col=rgb(1,0,0,1/4) )
I want to plot single bar in a graph so it would look like picture below
I created test data and calculate its mean.
value <- c(99,44,100,120,88)
value_mean <- mean(value)
And plot them using below code
barplot(value_mean, horiz=T, width=30, cex.names=0.5 ,ylim=c(0,200), col="red")
Buth the output is not even close.
I've also looked at this links
Single bar barchart in ggplot2, R
R Barplot with one bar - how to plot correctly
So my output should be something like the first picture. I was thinking that could solve ggplot.
If everything else fails, you can draw a rectangle like this:
par(mar = c(12, 2, 12, 2))
plot(0, type="n", ylim=c(-1, 1), xlim=c(0, 200), axes = F, bty = "n",ylab="", xlab="label")
rect(0, -.7, value_mean, .7, col="red", border=NA)
text(value_mean, 0, pos=4, label=value_mean)
axis(1, at=seq(0, 200, by=40))
I'm generating numerous plots with xlim and ylim values that I'm calculating on a per-plot basis. I want to put my legend outside the plot area (just above the box around the actual plot), but I can't figure out how to get the maximum y-value of the box around my plot area.
Is there a method for even doing this? I can move the legend where I want it by manually changing the legend() x and y values, but this takes a LONG time for the amount of graphs I'm creating.
Thanks!
-JM
Here's a basic example illustrating what I think you're looking for using one of the code examples from ?legend.
#Construct some data and start the plot
x <- 0:64/64
y <- sin(3*pi*x)
plot(x, y, type="l", col="blue")
points(x, y, pch=21, bg="white")
#Grab the plotting region dimensions
rng <- par("usr")
#Call your legend with plot = FALSE to get its dimensions
lg <- legend(rng[1],rng[2], "sin(c x)", pch=21,
pt.bg="white", lty=1, col = "blue",plot = FALSE)
#Once you have the dimensions in lg, use them to adjust
# the legend position
#Note the use of xpd = NA to allow plotting outside plotting region
legend(rng[1],rng[4] + lg$rect$h, "sin(c x)", pch=21,
pt.bg="white", lty=1, col = "blue",plot = TRUE, xpd = NA)
The command par('usr') will return the coordinates of the bounding box, but you can also use the grconvertX and grconvertY functions. A simple example:
plot(1:10)
par(xpd=NA)
legend(par('usr')[1], par('usr')[4], yjust=0, legend='anything', pch=1)
legend( grconvertX(1, from='npc'), grconvertY(1, from='npc'), yjust=0,
xjust=1, legend='something', lty=1)
The oma, omd, and omi arguments of par() control boundaries and margins of plots - they can be queried using par()$omd (etc). and set (if needed) using par(oma=c()) (where the vector can have up to 4 values - see ?par)