How can I rotate the X axis labels 45 degrees on a grouped bar plot in R?
I have tried the solution suggested here but got something very messy, the labels seem to have been added multiple times (only showing the axis part to protect data privacy):
This solution (gridBase) was also unsuccessful for me, for some reason I get the following error:
"Cannot pop the top-level viewport (grid and graphics output mixed?)"
PS.
Most people seem to recommend this solution in R base but I am stuck with that too because I don't understand what data they are referring to (I need some kind of example data set to understand new command lines...).
Are these solutions not working because my barplot is a grouped barplot? Or should it work nevertheless? Any suggestions are welcome, I have been stuck for quite some time. Thank you.
[edit] On request I am adding the code that I used to generate the picture above (based on one of the text() solutions):
data <- #this is a matrix with 4 columns and 20 rows;
#colnames and rownames are specified.
#the barplot data is grouped by rows
lablist <- as.vector(colnames(data))
barplot(data, beside=TRUE, col=c("darkred","red","grey20","grey40"))
text(1:100, par("usr")[1], labels=lablist, srt=45, pos=1, xpd=TRUE)
I am not a base plot proficient, so maybe my solution is not very simple. I think that using ggplot2 is better here.
def.par <- par(no.readonly = TRUE)
## divide device into two rows and 1 column
## allocate figure 1 for barplot
## allocate figure 2 for barplot labels
## respect relations between widths and heights
nf <- layout(matrix(c(1,1,2,2),2,2,byrow = TRUE), c(1,3), c(3,1), TRUE)
layout.show(nf)
## barplot
par(mar = c(0,1,1,1))
set.seed(1)
nKol <- 8 ## you can change here but more than 11 cols
## the solution is not really readable
data <- matrix(sample(1:4,nKol*4,rep=TRUE),ncol=nKol)
xx <- barplot(data, beside=TRUE,
col=c("darkred","red","grey20","grey40"))
## labels , create d ummy plot for sacles
par(mar = c(1,1,0,1))
plot(seq_len(length(xx)),rep(1,length(xx)),type='n',axes=FALSE)
## Create some text labels
labels <- paste("Label", seq_len(ncol(xx)), sep = " ")
## Plot text labels with some rotation at the top of the current figure
text(seq_len(length(xx)),rep(1.4,length(xx)), srt = 90, adj = 1,
labels = labels, xpd = TRUE,cex=0.8,srt=60,
col=c("darkred","red","grey20","grey40"))
par(def.par) #- reset to default
Try the first answer:
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)
But change cex=1 to cex=.8 or .6 in the text() function:
text(cex=.6, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45)
In the picture you posted, it appears to me that the labels are just too big. cex sets the size of these labels.
I had the same problem with a grouped bar plot. I assume that you only want one label below each group. I may be wrong about this, since you don't state it explicitly, but this seems to be the case since your labels are repeated in image. In that case you can use the solution proposed by Stu although you have to apply colMeans to the x variable when you supply it to the text function:
x <- barplot(table(mtcars$cyl), xaxt="n")
labs <- paste(names(table(mtcars$cyl)), "cylinders")
text(cex=1, x=colMeans(x)-.25, y=-1.25, labs, xpd=TRUE, srt=45)
Related
I'm trying to create a stripplot in which the name of my parameters on the x axis are greek letters. It is quite logical then that I want my plot to be label with greek letters and not "theta", "rho" and "tau" subscripts. My strategy is to hide the original labels and plot the greek letters on top. The following example shows what I have tried so far:
library(lattice)
data <- data.frame(Parameters=c("theta","rho","tau"),val1=c(1,2,4),val2=c(2,3,4))
png("plot.png")
stripplot(val1 + val2 ~ Parameters, data = data, pch=c(1,2), cex=2,
scales=list(cex=c(0,1.5)),
xlab=c(expression(rho),expression(tau),expression(theta)),
ylab=NULL,
xaxt='n',
)
dev.off()
But this piece of code weirdly eliminates the labels in the y axis too.
Try 1:
I also followed the advice in How to hide x-axis in lattice R but the results preserves the names in the x-axis.
Try 2:
How can I eliminate ONLY the labels on the x-axis without altering the y axis?
Have a look at the help page for ?stripplot, in particular the
scales argument.
Generally a list determining how the x- and y-axes (tick marks and labels) are drawn.
So use this argument to pass the size and labels argument for the x-axis.
stripplot(val1 + val2 ~ Parameters, data = dat, pch=c(1,2), cex=2,
scales=list(x=list(cex=1.5,
labels=c(expression(rho),expression(tau),expression(theta))
)))
This is clunky but would help if you had many x-axis elements.
labels=as.expression(sapply(levels(dat$Parameters), function(x) as.name(x)))
or
labels=parse(text=as.character(sort(dat$Parameters)))
library(lattice)
data <- data.frame(Parameters=c("theta","rho","tau"),val1=c(1,2,4),val2=c(2,3,4))
png("plot.png")
stripplot(val1 + val2 ~ Parameters, data = data, pch=c(1,2), cex=2,
scales=list(cex=c(0,1.5)),
xlab=c(expression(rho),expression(tau),expression(theta)),
xaxt='n',
)
dev.off()
I am trying to draw a barplot in R
I have 2 vectors
x <- c(1,2,3,4)
y <- c(200,400,4000,255)
A <- rbind(x,y) # to make it into a matrix
barplot(A, ylim= c(0,5000))
I want to put at the base of each plot 1,2,3,4 on the x axis.
How can I do that
Thanks
barplot(A, ylim= c(0,5000),names.arg=1:4)
This is how you do it.
My suggestion is that you should check the help manual/doc for each function carefully. R graphic functions usually have lots of arguments for various purposes.
Function "barplot" returns the x-axis value where each bar is centred. We can use these values as a reference to add legend on top of each bar, or any where else (but less straightforward).
To add on the top
x.axis <-barplot(A, ylim= c(0,5000),names.arg=1:4)
text(x.axis, y, adj = c(0.5, 0)) ## you have defined "y"
I would like to place asterisks in my grouped barplot (R base) to indicate where the paired comparisons differ significantly. I know how to place these stars using the points command. However, from the posts that I read sofar it seems that one needs to find the right coordinates manually (e.g., group I: x=0.635, y=26, see the code below). This would take quite some time if one needs to find that out for all significant pairs.
So my question is: Is there an easier way to find the coordinates that correspond with the mid and just next to paired bars? I would prefer to do this in base plotting system at the moment but ggplot answers are also welcome. Thank you very much in advance!
Data example
set.seed(123)
dat<-matrix(runif(32, min = 0.5, max = 1), nrow=2, ncol=16)
colnames(dat)<-c(LETTERS[1:16])
par(mar=c(2,4,2,2))
mp<-barplot(dat, col=c("blue","red"), beside=TRUE, horiz=TRUE, xpd=FALSE, axes=FALSE, axisnames=TRUE, cex.names=0.8, las=2, xlim=c(0.5,1.0), main="Data Example")
axis(1, at=seq(0.5,1.0, by=0.1))
axis(2, at=mp, labels=FALSE, tick=FALSE)
points(x=0.635, y=26, pch="*", cex=2) #sign position at I
Let's say you have a vector telling you which pairs are significant. For example:
sign <- rep(TRUE, 16) ; sign[c(5, 7, 13:14)] <- FALSE
you already know the y coordinates of the letters:
colMeans(mp)
so you can define the y coordinates of the asterisks:
ord_sign <- colMeans(mp)[sign]
For the x coordinates, you can place them for example 0.01 point to the right from the max value:
abs_sign <- apply(dat, 2, max)[sign] + 0.01
Then you can draw all your asterisks at once:
points(x=abs_sign, y=ord_sign, pch="*", cex=2)
I plot several lines on a graph using matplot:
matplot(cumsum(as.data.frame(daily.pnl)),type="l")
This gives me default colours for each line - which is fine,
But I now want to add a legend that reflects those same colours - how can I achieve that?
PLEASE NOTE - I am trying NOT to specify the colours to matplot in the first place.
legend(0,0,legend=spot.names,lty=1)
Gives me all the same colour.
The default color parameter to matplot is a sequence over the nbr of column of your data.frame. So you can add legend like this :
nn <- ncol(daily.pnl)
legend("top", colnames(daily.pnl),col=seq_len(nn),cex=0.8,fill=seq_len(nn))
Using cars data set as example, here the complete code to add a legend. Better to use layout to add the legend in a pretty manner.
daily.pnl <- cars
nn <- ncol(daily.pnl)
layout(matrix(c(1,2),nrow=1), width=c(4,1))
par(mar=c(5,4,4,0)) #No margin on the right side
matplot(cumsum(as.data.frame(daily.pnl)),type="l")
par(mar=c(5,0,4,2)) #No margin on the left side
plot(c(0,1),type="n", axes=F, xlab="", ylab="")
legend("center", colnames(daily.pnl),col=seq_len(nn),cex=0.8,fill=seq_len(nn))
I have tried to reproduce what you are looking for using the iris dataset. I get the plot with the following expression:
matplot(cumsum(iris[,1:4]), type = "l")
Then, to add a legend, you can specify the default lines colour and type, i.e., numbers 1:4 as follows:
legend(0, 800, legend = colnames(iris)[1:4], col = 1:4, lty = 1:4)
Now you have the same in the legend and in the plot. Note that you might need to change the coordinates for the legend accordingly.
I like the #agstudy's trick to have a nice legend.
For the sake of comparison, I took #agstudy's example and plotted it with ggplot2:
The first step is to "melt" the data-set
require(reshape2)
df <- data.frame(x=1:nrow(cars), cumsum(data.frame(cars)))
df.melted <- melt(df, id="x")
The second step looks rather simple in comparison to the solution with matplot
require(ggplot2)
qplot(x=x, y=value, color=variable, data=df.melted, geom="line")
Interestingly #agstudy solution does the trick, but only for n ≤ 6
Here we have a matrix with 8 columns. The colour of the first 6 labels are correct.
The 7th and 8th are wrong. The colour in the plots restarts from the beginning (black, red ...) , whereas in the label it continues (yellow, grey, ...)
Still haven't figured out why this is the case. I'll maybe update this post with my findings.
matplot(x = lambda, y = t(ridge$coef), type = "l", main="Ridge regression", xlab="λ", ylab="Coefficient-value", log = "x")
nr = nrow(ridge$coef)
legend("topright", rownames(ridge$coef), col=seq_len(nr), cex=0.8, lty=seq_len(nr), lwd=2)
Just discovered that matplot uses linetypes 1:5 and colors 1:6 to establish the appearance of the lines. If you want to create a legend try the following approach:
## Plot multiple columns of the data frame 'GW' with matplot
cstart = 10 # from column
cend = cstart + 20 # to column
nr <- cstart:cend
ltyp <- rep(1:5, times=length(nr)/5, each=1) # the line types matplot uses
cols <- rep(1:6, times=length(nr)/6, each=1) # the cols matplot uses
matplot(x,GW[,nr],type='l')
legend("bottomright", as.character(nr), col=cols, cex=0.8, lty=ltyp, ncol=3)
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