Y axis to percent using barplot [duplicate] - r

I'm plotting a graph using this
plot(dates,returns)
I would like to have the returns expressed as percentages instead of numbers. 0.1 would become 10%. Also, the numbers on the y-axis appear tilted 90 degrees on the left. Is it possible to make them appear horizontally?

Here is one way using las=TRUE to turn the labels on the y-axis and axis() for the new y-axis with adjusted labels.
dates <- 1:10
returns <- runif(10)
plot(dates, returns, yaxt="n")
axis(2, at=pretty(returns), lab=pretty(returns) * 100, las=TRUE)

If you use ggplot you can use the scales package.
library(scales)
plot + scale_y_continuous(labels = percent)

library(scales)
dates <- 1:100
returns <- runif(100)
yticks_val <- pretty_breaks(n=5)(returns)
plot(dates, returns, yaxt="n")
axis(2, at=yticks_val, lab=percent(yticks_val))
Highlights:
No need to explicitly add "%"
Manually fix the number of y-ticks to be consistent with further plots. Here I chose 5.
Combining two answers together #rengis #vladiim

Related

Stripcharts with same x-axis in R

I want to make a strip chart for each of the following two vectors with same x-axis using R.
Two vectors are:
x <- c(40,35,30,45,35,45,65,65,70,70)
y <- c(45,45,45,45,45,45,45,45,45,95)
When I made strip charts for the two, it came out like this:
How do I make it so that two x-axis will be the same?
Thank you
How do I make it so that two x-axis will be the same?
The stripchart() function takes an optional xlim parameter that lets you define the horizontal plot limits. For example:
x <- c(40,35,30,45,35,45,65,65,70,70)
y <- c(45,45,45,45,45,45,45,45,45,95)
par(bty="n", mfrow=c(2,1), mar=c(2,1,3,1)+0.1)
stripchart(x, xlim=c(20,100), method="stack", pch=16)
stripchart(y, xlim=c(20,100), method="stack", pch=21)

Base Plot, correctly defining axis [duplicate]

How can I change the spacing of tick marks on the axis of a plot?
What parameters should I use with base plot or with rgl?
There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):
Use par(xaxp = c(x1, x2, n)) or plot(..., xaxp = c(x1, x2, n)) to define the position (x1 & x2) of the extreme tick marks and the number of intervals between the tick marks (n). Accordingly, n+1 is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par.)
You can suppress the drawing of the axis altogether and add the tick marks later with axis().
To suppress the drawing of the axis use plot(... , xaxt = "n").
Then call axis() with side, at, and labels: axis(side = 1, at = v1, labels = v2). With side referring to the side of the axis (1 = x-axis, 2 = y-axis), v1 being a vector containing the position of the ticks (e.g., c(1, 3, 5) if your axis ranges from 0 to 6 and you want three marks), and v2 a vector containing the labels for the specified tick marks (must be of same length as v1, e.g., c("group a", "group b", "group c")). See ?axis and my updated answer to a post on stats.stackexchange for an example of this method.
With base graphics, the easiest way is to stop the plotting functions from drawing axes and then draw them yourself.
plot(1:10, 1:10, axes = FALSE)
axis(side = 1, at = c(1,5,10))
axis(side = 2, at = c(1,3,7,10))
box()
I have a data set with Time as the x-axis, and Intensity as y-axis. I'd need to first delete all the default axes except the axes' labels with:
plot(Time,Intensity,axes=F)
Then I rebuild the plot's elements with:
box() # create a wrap around the points plotted
axis(labels=NA,side=1,tck=-0.015,at=c(seq(from=0,to=1000,by=100))) # labels = NA prevents the creation of the numbers and tick marks, tck is how long the tick mark is.
axis(labels=NA,side=2,tck=-0.015)
axis(lwd=0,side=1,line=-0.4,at=c(seq(from=0,to=1000,by=100))) # lwd option sets the tick mark to 0 length because tck already takes care of the mark
axis(lwd=0,line=-0.4,side=2,las=1) # las changes the direction of the number labels to horizontal instead of vertical.
So, at = c(...) specifies the collection of positions to put the tick marks. Here I'd like to put the marks at 0, 100, 200,..., 1000. seq(from =...,to =...,by =...) gives me the choice of limits and the increments.
And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:
plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th

Segmenting X-axis label in an R plot

I've been working extensively with R lately and I have a nitpicky plotting question.
I've attached an image of my current plot as reference. As you can see, I've added vertical lines to segment parts of my data inputs. I have 200 'agents' and each of them comes from different categorical subsets which make them all a little different. So, my goal is to keep the bottom axis as the index of my 'agents' vector, but I'd like to add a label to each of my subdivisions at the bottom to make it a little clearer as to why I'm segmenting them with the vertical lines.
Any suggestions?
http://i.imgur.com/YGNdBhg.png?1?1971
You just need to call axis like this:
x = sin(1:100) + rnorm(100, 0,.125)
breaks = c(10,33,85, 96)
plot(x)
sapply(breaks, function(x){abline(v=x, lty=2)})
axis(1, breaks, as.character(breaks))
If you don't want the default ticks plotted at all (i.e. just the ticks in the "breaks" vector) you just need to modify this slightly:
plot(x, axes=F)
sapply(breaks, function(x){abline(v=x, lty=2)})
axis(1, breaks, as.character(breaks))
axis(2)
box()
You don't provide any example data or code, so the code I am sending is untested. I am calling the vector of vertical lines vertlines and the vector of labels labels. I define the midpoints of each category using the vertlines and the range of the agent values. Then I add them to the plot using the mtext() function. Give it a try.
vertlines <- c(40, 80, 120, 140, 160, 180)
labels <- letters[1:7]
labelx <- diff(c(1, vertlines, 200))/2 + c(1, vertlines)
mtext(labels, at=labelx, side=1, line=4)

Plot percentages on y-axis

I'm plotting a graph using this
plot(dates,returns)
I would like to have the returns expressed as percentages instead of numbers. 0.1 would become 10%. Also, the numbers on the y-axis appear tilted 90 degrees on the left. Is it possible to make them appear horizontally?
Here is one way using las=TRUE to turn the labels on the y-axis and axis() for the new y-axis with adjusted labels.
dates <- 1:10
returns <- runif(10)
plot(dates, returns, yaxt="n")
axis(2, at=pretty(returns), lab=pretty(returns) * 100, las=TRUE)
If you use ggplot you can use the scales package.
library(scales)
plot + scale_y_continuous(labels = percent)
library(scales)
dates <- 1:100
returns <- runif(100)
yticks_val <- pretty_breaks(n=5)(returns)
plot(dates, returns, yaxt="n")
axis(2, at=yticks_val, lab=percent(yticks_val))
Highlights:
No need to explicitly add "%"
Manually fix the number of y-ticks to be consistent with further plots. Here I chose 5.
Combining two answers together #rengis #vladiim

Labelling logarithmic scale display in R

While plotting histogarm, scatterplots and other plots with axes scaled to logarithmic scale in R, how is it possible to use labels such as 10^-1 10^0 10^1 10^2 10^3 and so on instead of the axes showing just -1, 0, 1, 2, 3 etc. What parameters should be added to the commands such as hist(), plot() etc?
Apart from the solution of ggplot2 (see gsk3's comment), I would like to add that this happens automatically in plot() as well when using the correct arguments, eg :
x <- 1:10
y <- exp(1:10)
plot(x,y,log="y")
You can use the parameter log="x" for the X axis, or log="xy" for both.
If you want to format the numbers, or you have the data in log format, you can do a workaround using axis(). Some interesting functions :
axTicks(x) gives you the location of the ticks on the X-axis (x=1) or Y-axis (x=2)
bquote() converts expressions to language, but can replace a variable with its value. More information on bquote() in the question Latex and variables in plot label in R? .
as.expression() makes the language object coming from bquote() an expression. This allows axis() to do the formatting as explained in ?plotmath. It can't do so with language objects.
An example for nice formatting :
x <- y <- 1:10
plot(x,y,yaxt="n")
aty <- axTicks(2)
labels <- sapply(aty,function(i)
as.expression(bquote(10^ .(i)))
)
axis(2,at=aty,labels=labels)
Which gives
Here is a different way to draw this type of axis:
plot(NA, xlim=c(0,10), ylim=c(1, 10^4), xlab="x", ylab="y", log="y", yaxt="n")
at.y <- outer(1:9, 10^(0:4))
lab.y <- ifelse(log10(at.y) %% 1 == 0, at.y, NA)
axis(2, at=at.y, labels=lab.y, las=1)
EDIT: This is also solved in latticeExtra with scale.components
In ggplot2 you just can add a
... +
scale_x_log10() +
scale_y_log10(limits = c(1e-4,1), breaks=c(1e-4,1e-3,1e-2,0.1,1)) + ...
to scale your axis, Label them and add custom breaks.

Resources