I want to plot data in a graph with larger font-size for the lables.
x = c(0:10)
y = sin(x) + 10
plot (
x, y, type="o",
xlab = "X values",
ylab = "Y values",
cex.axis = "2",
cex.lab = "2",
las = 1
)
Unfortunately the numbers on the y-axis overlap the label for the y-axis. I tried to use mar, but that did not work (By the way, how can I find out which graphic parameters can be directly used in the plot command and which have to be set with the par()-method? ).
How can I avoid that labels overlap?
Thanks for your help.
Sven
Use par(mar) to increase the plot margins and par(mgp) to move the axis label.
par(mar = c(6.5, 6.5, 0.5, 0.5), mgp = c(5, 1, 0))
#Then call plot as before
In the help page ?par it explains which parameters can be used directly in plot and which must be called via par.
There are several parameters can only be set by a call to ‘par()’:
• ‘"ask"’,
• ‘"fig"’, ‘"fin"’,
• ‘"lheight"’,
• ‘"mai"’, ‘"mar"’, ‘"mex"’, ‘"mfcol"’, ‘"mfrow"’, ‘"mfg"’,
• ‘"new"’,
• ‘"oma"’, ‘"omd"’, ‘"omi"’,
• ‘"pin"’, ‘"plt"’, ‘"ps"’, ‘"pty"’,
• ‘"usr"’,
• ‘"xlog"’, ‘"ylog"’
The remaining parameters can also be set as arguments (often via
‘...’) to high-level plot functions such as ‘plot.default’,
‘plot.window’, ‘points’, ‘lines’, ‘abline’, ‘axis’, ‘title’,
‘text’, ‘mtext’, ‘segments’, ‘symbols’, ‘arrows’, ‘polygon’,
‘rect’, ‘box’, ‘contour’, ‘filled.contour’ and ‘image’. Such
settings will be active during the execution of the function,
only. However, see the comments on ‘bg’ and ‘cex’, which may be
taken as _arguments_ to certain plot functions rather than as
graphical parameters.
The quick and dirty way would be to use par and add a newline in ylab, even though it's conceptually terrible.
x = 0:10
y = sin(x) + 10
par(mar=c(5,7,4,2))
plot (
x, y, type="o",
xlab = "X values",
ylab = "Y values\n",
cex.axis = "2",
cex.lab = "2",
las = 1
)
Concerning which parameters you can set directly in plot have a look at ?plot.default and ?plot.xy as they will recieve the ... arugments. There's also a couple of calls to undocumented functions (as far as I can find) like localWindow and localBox but I don't know what happens to them. I'd guess they're just ignored.
You can put the mgp parameter into the title() function to avoid having to reset your defaults afterwards. That way the parameter only acts on the label(s) added by the function. like this:
plot (
x, y, type="o",
xlab = "", #Don't include xlab in main plot
ylab = "Y values",
cex.axis = "2",
cex.lab = "2",
las = 1
)
title(xlab="X values"
,mgp=c(6,1,0)) #Set the distance of title from plot to 6 (default is 3).
Related
I am trying to get the x axis labels to be rotated 45 degrees on a barplot with no luck. This is the code I have below:
barplot(((data1[,1] - average)/average) * 100,
srt = 45,
adj = 1,
xpd = TRUE,
names.arg = data1[,2],
col = c("#3CA0D0"),
main = "Best Lift Time to Vertical Drop Ratios of North American Resorts",
ylab = "Normalized Difference",
yaxt = 'n',
cex.names = 0.65,
cex.lab = 0.65)
use optional parameter las=2 .
barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)
EDITED ANSWER PER DAVID'S RESPONSE:
Here's a kind of hackish way. I'm guessing there's an easier way. But you could suppress the bar labels and the plot text of the labels by saving the bar positions from barplot and do a little tweaking up and down. Here's an example with the mtcars data set:
x <- barplot(table(mtcars$cyl), xaxt="n")
labs <- paste(names(table(mtcars$cyl)), "cylinders")
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45)
Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:
par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels
#use mtcars dataset to produce a barplot with qsec colum information
mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"
end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)
barplot(mtcars$qsec, col = "grey50",
main = "",
ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
xlab = "",
xaxt = "n", # Do not plot the default labels
space = 1)
#rotate 60 degrees (srt = 60)
text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25,
srt = 60, adj = 1, xpd = TRUE,
labels = paste(rownames(mtcars)), cex = 0.65)
You can simply pass your data frame into the following function:
rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Usage:
rotate_x(mtcars, 'mpg', row.names(mtcars), 45)
You can change the rotation angle of the labels as needed.
You may use
par(las=2) # make label text perpendicular to axis
It is written here: http://www.statmethods.net/graphs/bar.html
You can use ggplot2 to rotate the x-axis label adding an additional layer
theme(axis.text.x = element_text(angle = 90, hjust = 1))
In the documentation of Bar Plots we can read about the additional parameters (...) which can be passed to the function call:
... arguments to be passed to/from other methods. For the default method these can
include further arguments (such as axes, asp and main) and graphical
parameters (see par) which are passed to plot.window(), title() and axis.
In the documentation of graphical parameters (documentation of par) we can see:
las
numeric in {0,1,2,3}; the style of axis labels.
0:
always parallel to the axis [default],
1:
always horizontal,
2:
always perpendicular to the axis,
3:
always vertical.
Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.
That is why passing las=2 makes the labels perpendicular, although not at 45°.
Andre Silva's answer works great for me, with one caveat in the "barplot" line:
barplot(mtcars$qsec, col="grey50",
main="",
ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
xlab = "",
xaxt = "n",
space=1)
Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.
I am trying to plot few graphs using loops. I am now describing in details.
First I have a function which is calculates the y-variable (called effect for vertical axis)
effect<- function (x, y){
exp(-0.35*log(x)
+0.17*log(y)
-0.36*sqrt(log(x)*log(y)/100))
}
Now I run the following code and use the option par to plot the lines in the same graph. I use axis=FALSE and xlab="" to get a plot without labels. I do this so that my labels are not re-written each time the loop runs and looks ugly.
for (levels in seq(exp(8), exp(10), length.out = 5)){
x = seq(exp(1),exp(10), length.out = 20)
prc= effect(levels,x)
plot(x, prc,xlim = c(0,max(x)*1.05), ylim=c(0.0,0.3),
type="o", xlab = "",ylab = "", pch = 16,
col = "dark blue", lwd = 2, cex = 1, axes = F)
label = as.integer(levels) #x variable
text(max(x)*1.03,max(prc), label )
par(new=TRUE)
}
Finally, I duplicate the plot command this time using the xlab and ylab options
plot(x, prc, xlab = "X-label", ylab = "effect",
xlim = c(0,max(x)*1.05), ylim = c(0,0.3),
type="l", col ='blue')
I have several other plots in the similar lines, using complex equations. I have two questions:
Is there an better option to have the same plot with smoother lines?
Is there an easier option with few lines to achieve the same, where I can place the texts (levels) for each line on the right with white background at the back?
I believe working with the plot function was tedious and time consuming. So, I have finally used ggplot2 to plot. There were several help available online, which I have used.
I want to omit the x-axis labels for my plot of means, but I just fail (I didn't use packages such as ggplot2):
with(richness_formok,plotMeans(barklicerare,invstatus,error.bars="conf.int", level=0.95, xlab="", ylab="", main="")) # normal code
with(richness_formok,plotMeans(barklicerare,invstatus,error.bars="conf.int", level=0.95, xlab="", ylab="", main="",frame=F)) # which gives no response
with(richness_formok,plotMeans(barklicerare,invstatus,error.bars="conf.int", level=0.95, xlab="", ylab="", main="",axes=F))
This gives the following error:
Error in plot.default(c(1, n.levs), yrange, type = "n", xlab = xlab, ylab = ylab, :
formal argument "axes" matched by multiple actual arguments
The below code temporarily sets the color of axis tick labels (i.e., for both the x and y-axis) to "transparent" using par, thus preventing the automatically drawn tick labels from being visible. The y-axis tick labels can easily be inserted afterwards by reverting the par-related modifications.
## sample data
library(Rcmdr)
data(Moore)
## create plot with transparent (i.e., non-visible) tick labels
par(col.axis = "transparent")
with(Moore, plotMeans(conformity, fcategory, partner.status,
ylim = c(0, 25)))
## add y-axis tick labels
par(col.axis = "black")
axis(side = 2, at = seq(0, 25, 5), tick = FALSE)
Remember that this is a rather undesired behavior of plotMeans since the help pages explicitly say that ... are arguments to be passed on to plot. Therefore, if your target is to entirely disable the drawing of the frame and axes when using plotMeans, e.g. similar to the visual output of plot(1:10, 1:10, axes = FALSE), you should probably file a bug report.
Update
In case I understood it wrongly and you actually wanted to remove both the tick labels and the ticks, you could simply use
par(xaxt = "n")
with(Moore, plotMeans(conformity, fcategory, partner.status,
ylim = c(0, 25)))
See also ?par for further possible modifications of R base plots.
I have a problem changing the text size of a 3d plot I generated with the package rgl. Everything works fine, but I can't effectively change the cex and size properties of an 3d object when rendering it in shiny, with the renderWebGL
library(rgl)
plot3d(x, y, z, xlab ="x", ylab ="y", zlab ="z")
texts3d(x, y, z, rownames(data))
Any help is highly appreciated! Best Regards.
Brecht
You can scale the text (including axis labels) by changing the "cex" rgl parameter, by calling the function par3d. The "cex" rgl parameter is different from the "cex" parameter in base graphics.
For example, if you want to magnify the text in your plot by a factor of 2, then you can call:
par3d(cex=2.0)
with(iris,
plot3d(Sepal.Length, Sepal.Width, Petal.Length,
type="s", col=as.numeric(Species)))
Note that calling par3d opens a plotting window. Calling a plotting function creates a plot in that same window. You have to call par3d every time you create a new plot. The function par3d can also change many other rgl parameters.
I ran into similar problems with library plot functions from PerformanceAnalytics. I would advise to get the code for the function by typing plot3d in the console and looking at the original plot functions inside.
It might be the case that the plot3d function doesn't pass a cex option forward, so you can also copy the function and modify it to make it your own myplot3d function or something like that.
For anyone still trying to address this issue, the plot3D package takes care of this nicely now.
See the following reproducible code.
# Load plot3D package
library(plot3D)
Using the iris dataset, let's make a 3D graph. See our use of cex, cex.main, and cex.lab at the end, which allow us to multiply text size, all within the package.
scatter3D(
x = iris$Sepal.Length,
y = iris$Sepal.Width,
z = iris$Petal.Length,
# Add a nice background
bty = "u",
col.grid = "darkgrey",
col.panel = "black",
# Specify Labels
main = "My graph",
clab = "Petal\nLength",
xlab = "\nSepal Length",
ylab = "\nSepal Width",
zlab = "\nPetal Length",
# Adjust label sizing
cex = 2, # Multiply dot size by 2
cex.main = 2, # Multiply the size of main title text by 2
cex.lab = 2) # Multiply size of axis label text by 2
Or, we can shrink the text size back to normal, here:
scatter3D(
x = iris$Sepal.Length,
y = iris$Sepal.Width,
z = iris$Petal.Length,
# Add a nice background
bty = "u",
col.grid = "darkgrey",
col.panel = "black",
# Specify Labels
main = "My graph",
clab = "Petal\nLength",
xlab = "\nSepal Length",
ylab = "\nSepal Width",
zlab = "\nPetal Length",
# Adjust label sizing
cex = 1, # Multiply dot size by 2
cex.main = 1, # Multiply the size of main title text by 2
cex.lab = 1) # Multiply size of axis label text by 2
Not the OP situation but if you need to change the text size on a rgl plot and your text is a LaTeX expression you have to pass the text size parameter (cex) to the corresponding function.
For example,
library(rgl)
library(magrittr)
iris %>%
{points3d('x'=.$Sepal.Length, 'y'=.$Sepal.Width, z=.$Petal.Length)}
title3d(main=NULL, sub=setName,
xlab=latex2exp::TeX(r"($\phi_{\pi})"),
ylab=latex2exp::TeX(r"($\phi_{X}$)"),
zlab=latex2exp::TeX(r"($\psi_{B}$)"),
cex=4)
Notice the cex argument in title3d() which is passed to plotmath3d() which actually draws the LaTeX expression into a PNG file that is then paste on the final plot. See the documentation for plotmath3d for details but cex is a number that scales the text size.
Anybody know how to set the minimum and maximum values for x-axis when running logi.hist.plot in popbio package in R?
At the moment, the minimum value is defined as my minimum data value. I want it to be 0.
library(popbio)
logi.hist.plot(data$Heat, data$Death, logi.mod = 1,
boxp = FALSE,type="hist", col="gray",
ylabel = "Probability of death",
ylabel2 = "Death Frequency",
xlabel = "Heat",
mainlabel = "Logistic probability plot of Heat vs Death")
You have not offered a dataset for testing possible solutions to this request, but I offer an idea:
First make a plot that basically sets up the desired limits with xlim and ylim as desired, and blank x- and y-labels and axt="n",
...then issue par(new=TRUE),
...then run your plot function.
Taking a quick look at the source code - just type logi.hist.plot - it isn't possible to change the axis limits.
The source code is fairly long, but not that complicated. Essentially, the boxp=FALSE option calls this part of code:
logi.scater <- function(independ, depend, scater = "n", x.lab = xlabel,
las = las.h) {
plot(independ, depend, cex = 1, type = scater, ylab = ylabel,
xlab = x.lab, main = mainlabel, cex.lab = 1.2, las = las)
}
You can see that the plot function doesn't allow limits to be passed.
You options are:
Take apart the source code and construct your own plot.
Decided you are happy with the axis.