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)
Related
I want to plot a line chart. Depending on values it should change its color.
What I found is:
plot(sin(seq(from=1, to=10,by=0.1)),type="p",
col=ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","yellow"))
That works. But as soon as I change from type="p" to type="l" the conditional colouring disappears.
Is that behavior intended?
What is a solution with base graphics to plot a functional line with different colors?
Use segments instead of lines.
The segments function will only add to an existing plot. To create a blank plot with the correct axes and limits, first use plot with type="n" to draw "nothing".
x0 <- seq(1, 10, 0.1)
colour <- ifelse(sin(seq(from=1, to=10,by=0.1))>0.5,"red","blue")
plot(x0, sin(x0), type="n")
segments(x0=x0, y0=sin(x0), x1=x0+0.1, y1=sin(x0+0.1), col=colour)
See ?segments for more detail.
Here is a little different approach:
x <- seq(from=1, to=10, by=0.1)
plot(x,sin(x), col='red', type='l')
clip(1,10,-1,.5)
lines(x,sin(x), col='yellow', type='l')
Note that with this method the curve changes colors at exactly 0.5.
After you've drawn a line plot, you can color it with segments():
seq1 <- seq(from=1, to=10, by=0.1)
values <- sin(seq1)
s <- seq(length(seq1)-1)
segments(seq1[s], values[s], seq1[s+1], values[s+1], col=ifelse(values > 0.5, "red", "yellow"))
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()
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)
I have created a scatter plot with circle size changing with the intensity of the data: Fro 0 to 2, from 2 to 4,.. from 8 to 10. Does anyone could help me to create the proper legend for my plot?.
My code is:
require(xlsx)
data <- read.xlsx("data.xlsx", 1, header=TRUE) # reading the data
BRfunc <- colorRampPalette(c("blue", "red")) # the color gradient
itvl <- c(0,2,4,6,8,10)
plot(data$years, data$cars, cex=findInterval(data$emission, itvl), col="black" )
I've created a reproducible data set
n <- 50
data <- data.frame(years=1950+(1:n), cars=rnorm(n), emission=runif(n,0,10))
Then use your code to plot the figure
itvl <- c(0,2,4,6,8,10)
plot(data$years, data$cars, cex=findInterval(data$emission, itvl), col="black" )
To be able to create the legend, I've used legend() as Marc in the box suggested.
legend("topright", legend=itvl, pt.cex=itvl, pch=1)
You can use options such as xjust and x.intersp to change the spacing between the symbols and legend. You can use bty to remove the box.
I have a numeric vector and wish to plot each value on y-axis by their name on the x-axis.
Example:
quantity <- c(3,5,2)
names(quantity) <- c("apples","bananas", "pears")
plot(quantity)
Each value is plotted with it's index number along the x-axis ie. 1,2,3. How can I get it to show ("apples","bananas", "pears")?
You can use function axis() to add labels. Argument xaxt="n" inside plot() will make plot without x axis labels (numbers).
plot(quantity,xaxt="n")
axis(1,at=1:3,labels=names(quantity))
Do you look for barplot?
barplot(quantity)
And another option using lattice:
library(lattice)
barchart(quantity)
I had this same problem so I found this question, but once I looked at the answers and saw you could use names(named.vector) to get the names from the named.vector. Then I tried this and it worked.
plot(x = quantity, y = names(quantity))
I feel this is cleaner and simpler than a lot of the answers on this question. Even the one that was accepted.
You can use either barplot or ggplot2 and have a graph of the following
quantity <- c(3, 5, 2)
names(quantity) <- c("apples", "banans", "pears")
barplot(quantity, main="Fruit Names vs. Quantity", xlab = "Names", ylab="Quantity", col=c("blue", "red", "yellow"))
legend("topright", legend=c("apples", "banas", "pears"), fill=c("blue", "red", "yellow"))