How to automatically generate legend for line graphs in R - r
all,
I have following R script. To give credit, it's based on a script I got from http://www.statmethods.net/graphs/line.html, and applied to my own data. Perhaps you can tell that I am new to R. Following script generates auto legend and labels it as 1,2,3. Instead I want the script to print "sample names as text" instead of numbers. I was wondering if anyone can help me with this. Thank you.
# Create Line Chart
fd<- read.csv ("indata", header=TRUE)
## convert factor to numeric for convenience
fd$sampleN <- as.numeric(fd$sampleN)
nfd <- max(fd$sampleN)
# get the range for the x and y axis
xrange <- range(fd$gc)
#yrange <- range(fd$coverage)
yrange <- range(0,2) #you can customize this one.
# set up the plot
plot(xrange, yrange, type="n", xlab="gc", ylab="nc" )
colors <- rainbow(nfd)
linetype <- c(1:nfd)
plotchar <- seq(18,18+nfd,1)
# add lines
for (i in 1:nfd) {
tree <- subset(fd, sampleN==i)
lines(tree$gc, tree$coverage, type="b", lwd=1.5,
lty=linetype[i], col=colors[i], pch=plotchar[i])
}
# add a title and subtitle
title("metrics", "")
# add a legend
legend(xrange[1], yrange[2], 1:nfd, cex=0.8, col=colors,
pch=plotchar, lty=linetype, title="Samples")
Input data is below:
sampleN,gc,coverage
sample_metrics1,0,0.24558
sample_metrics1,1,0.05663
sample_metrics1,2,0.088432
sample_metrics1,3,0.117296
sample_metrics1,4,0.169752
sample_metrics1,5,0.228159
sample_metrics1,6,0.333096
sample_metrics1,7,0.427725
sample_metrics1,8,0.428772
sample_metrics1,9,0.502811
sample_metrics1,10,0.580475
sample_metrics1,11,0.649858
sample_metrics1,12,0.686928
sample_metrics1,13,0.76773
sample_metrics1,14,0.817875
sample_metrics1,15,0.862198
sample_metrics1,16,0.878292
sample_metrics1,17,0.90871
sample_metrics1,18,0.910914
sample_metrics1,19,0.949483
sample_metrics1,20,0.931209
sample_metrics1,21,0.935704
sample_metrics1,22,0.945239
sample_metrics1,23,0.927157
sample_metrics1,24,0.930656
sample_metrics1,25,0.935901
sample_metrics1,26,0.932245
sample_metrics1,27,0.934365
sample_metrics1,28,0.937328
sample_metrics1,29,0.94063
sample_metrics1,30,0.943312
sample_metrics1,31,0.950184
sample_metrics1,32,0.963963
sample_metrics1,33,0.984982
sample_metrics1,34,1.003258
sample_metrics1,35,1.023331
sample_metrics1,36,1.045045
sample_metrics1,37,1.057649
sample_metrics1,38,1.067116
sample_metrics1,39,1.067653
sample_metrics1,40,1.063026
sample_metrics1,41,1.052287
sample_metrics1,42,1.040282
sample_metrics1,43,1.020074
sample_metrics1,44,1.000212
sample_metrics1,45,0.9896
sample_metrics1,46,0.985244
sample_metrics1,47,0.985526
sample_metrics1,48,0.982893
sample_metrics1,49,0.981362
sample_metrics1,50,0.979265
sample_metrics1,51,0.979916
sample_metrics1,52,0.979846
sample_metrics1,53,0.984885
sample_metrics1,54,0.986803
sample_metrics1,55,0.994042
sample_metrics1,56,0.996345
sample_metrics1,57,1.007551
sample_metrics1,58,1.003795
sample_metrics1,59,1.008586
sample_metrics1,60,1.01787
sample_metrics1,61,1.02482
sample_metrics1,62,1.020601
sample_metrics1,63,1.018051
sample_metrics1,64,1.035102
sample_metrics1,65,1.025948
sample_metrics1,66,1.03562
sample_metrics1,67,1.040274
sample_metrics1,68,1.036387
sample_metrics1,69,1.058105
sample_metrics1,70,1.06795
sample_metrics1,71,1.064344
sample_metrics1,72,1.049132
sample_metrics1,73,1.071662
sample_metrics1,74,1.08023
sample_metrics1,75,1.09954
sample_metrics1,76,1.14631
sample_metrics1,77,1.172438
sample_metrics1,78,1.175826
sample_metrics1,79,1.211766
sample_metrics1,80,1.208507
sample_metrics1,81,1.217303
sample_metrics1,82,1.262392
sample_metrics1,83,1.331984
sample_metrics1,84,1.383047
sample_metrics1,85,1.416259
sample_metrics1,86,1.583698
sample_metrics1,87,1.785849
sample_metrics1,88,1.857123
sample_metrics1,89,2.114804
sample_metrics1,90,1.991428
sample_metrics1,91,1.976769
sample_metrics1,92,2.216659
sample_metrics1,93,1.606086
sample_metrics1,94,1.821604
sample_metrics1,95,5.19378
sample_metrics1,96,2.46372
sample_metrics1,97,9.844896
sample_metrics1,98,17.281094
sample_metrics1,99,10.147151
sample_metrics1,100,0
sample_metrics2,0,0.27566
sample_metrics2,1,0.052443
sample_metrics2,2,0.060661
sample_metrics2,3,0.142456
sample_metrics2,4,0.110315
sample_metrics2,5,0.195035
sample_metrics2,6,0.266574
sample_metrics2,7,0.256115
sample_metrics2,8,0.332823
sample_metrics2,9,0.341872
sample_metrics2,10,0.335247
sample_metrics2,11,0.480877
sample_metrics2,12,0.40355
sample_metrics2,13,0.452441
sample_metrics2,14,0.522209
sample_metrics2,15,0.489945
sample_metrics2,16,0.51272
sample_metrics2,17,0.538931
sample_metrics2,18,0.58408
sample_metrics2,19,0.600836
sample_metrics2,20,0.615026
sample_metrics2,21,0.631172
sample_metrics2,22,0.651189
sample_metrics2,23,0.653251
sample_metrics2,24,0.679981
sample_metrics2,25,0.69569
sample_metrics2,26,0.71077
sample_metrics2,27,0.735305
sample_metrics2,28,0.754265
sample_metrics2,29,0.778111
sample_metrics2,30,0.804297
sample_metrics2,31,0.831779
sample_metrics2,32,0.863024
sample_metrics2,33,0.894018
sample_metrics2,34,0.937245
sample_metrics2,35,0.985043
sample_metrics2,36,1.029299
sample_metrics2,37,1.069061
sample_metrics2,38,1.094257
sample_metrics2,39,1.102138
sample_metrics2,40,1.114504
sample_metrics2,41,1.11484
sample_metrics2,42,1.111952
sample_metrics2,43,1.108918
sample_metrics2,44,1.090665
sample_metrics2,45,1.082678
sample_metrics2,46,1.076516
sample_metrics2,47,1.08798
sample_metrics2,48,1.093462
sample_metrics2,49,1.08452
sample_metrics2,50,1.090786
sample_metrics2,51,1.093115
sample_metrics2,52,1.101703
sample_metrics2,53,1.107301
sample_metrics2,54,1.11793
sample_metrics2,55,1.130198
sample_metrics2,56,1.141167
sample_metrics2,57,1.155742
sample_metrics2,58,1.165464
sample_metrics2,59,1.157386
sample_metrics2,60,1.167818
sample_metrics2,61,1.166827
sample_metrics2,62,1.135574
sample_metrics2,63,1.128703
sample_metrics2,64,1.130197
sample_metrics2,65,1.089628
sample_metrics2,66,1.048679
sample_metrics2,67,1.024862
sample_metrics2,68,0.951014
sample_metrics2,69,0.863408
sample_metrics2,70,0.741022
sample_metrics2,71,0.661516
sample_metrics2,72,0.545033
sample_metrics2,73,0.433509
sample_metrics2,74,0.367888
sample_metrics2,75,0.275933
sample_metrics2,76,0.148513
sample_metrics2,77,0.104557
sample_metrics2,78,0.09074
sample_metrics2,79,0.035399
sample_metrics2,80,0.038729
sample_metrics2,81,0.013173
sample_metrics2,82,0.011767
sample_metrics2,83,0.019057
sample_metrics2,84,0.012294
sample_metrics2,85,0
sample_metrics2,86,0
sample_metrics2,87,0
sample_metrics2,88,0
sample_metrics2,89,0
sample_metrics2,90,0
sample_metrics2,91,0
sample_metrics2,92,0
sample_metrics2,93,0
sample_metrics2,94,0
sample_metrics2,95,6.012146
sample_metrics2,96,0
sample_metrics2,97,10.129887
sample_metrics2,98,5.080385
sample_metrics2,99,12.529071
sample_metrics2,100,0
genome_windows,0,0.000831175
genome_windows,1,0.000594994
genome_windows,2,0.0006862
genome_windows,3,0.000876388
genome_windows,4,0.000942013
genome_windows,5,0.000958863
genome_windows,6,0.001091706
genome_windows,7,0.001176513
genome_windows,8,0.001343131
genome_windows,9,0.001520906
genome_windows,10,0.001799756
genome_windows,11,0.002206363
genome_windows,12,0.002886519
genome_windows,13,0.003815775
genome_windows,14,0.005416344
genome_windows,15,0.007978863
genome_windows,16,0.011943919
genome_windows,17,0.017942331
genome_windows,18,0.026916138
genome_windows,19,0.039731306
genome_windows,20,0.057394938
genome_windows,21,0.080734088
genome_windows,22,0.110251175
genome_windows,23,0.146365406
genome_windows,24,0.188943563
genome_windows,25,0.236974131
genome_windows,26,0.288641038
genome_windows,27,0.342599325
genome_windows,28,0.397027756
genome_windows,29,0.449998694
genome_windows,30,0.500295781
genome_windows,31,0.546689806
genome_windows,32,0.587357375
genome_windows,33,0.621426481
genome_windows,34,0.647914206
genome_windows,35,0.66795535
genome_windows,36,0.680710806
genome_windows,37,0.684866219
genome_windows,38,0.678578188
genome_windows,39,0.663729056
genome_windows,40,0.642785275
genome_windows,41,0.617580269
genome_windows,42,0.5895275
genome_windows,43,0.561500825
genome_windows,44,0.536200638
genome_windows,45,0.514647113
genome_windows,46,0.496522031
genome_windows,47,0.481198119
genome_windows,48,0.465125163
genome_windows,49,0.445097106
genome_windows,50,0.419522256
genome_windows,51,0.389562975
genome_windows,52,0.358433044
genome_windows,53,0.329269363
genome_windows,54,0.30327115
genome_windows,55,0.280368106
genome_windows,56,0.258316269
genome_windows,57,0.234869275
genome_windows,58,0.209039444
genome_windows,59,0.181009944
genome_windows,60,0.152880644
genome_windows,61,0.126921669
genome_windows,62,0.104752206
genome_windows,63,0.086465069
genome_windows,64,0.071383019
genome_windows,65,0.058826631
genome_windows,66,0.048428619
genome_windows,67,0.039328369
genome_windows,68,0.031444125
genome_windows,69,0.025158775
genome_windows,70,0.020178806
genome_windows,71,0.01616445
genome_windows,72,0.013079681
genome_windows,73,0.0106774
genome_windows,74,0.008807444
genome_windows,75,0.007423456
genome_windows,76,0.006410344
genome_windows,77,0.005637675
genome_windows,78,0.005014725
genome_windows,79,0.0043783
genome_windows,80,0.003736631
genome_windows,81,0.003142294
genome_windows,82,0.002639056
genome_windows,83,0.002170913
genome_windows,84,0.001683113
genome_windows,85,0.001218638
genome_windows,86,0.000809938
genome_windows,87,0.000524731
genome_windows,88,0.000361769
genome_windows,89,0.000234463
genome_windows,90,0.000153681
genome_windows,91,9.75E-05
genome_windows,92,0.000057575
genome_windows,93,3.61E-05
genome_windows,94,0.00002095
genome_windows,95,1.03E-05
genome_windows,96,6.16E-06
genome_windows,97,4.11E-06
genome_windows,98,0.00000205
genome_windows,99,8.31E-07
genome_windows,100,2.12E-06
I would use ggplot2 for this:
library(ggplot2)
ggplot(fd, aes(x = gc, y = coverage, color = sampleN)) +
geom_line()
This uses the names of factor in the legend, in your case sample_metrics1, etc.
From ?legend, you can see that the third argument (currently 1:nfd) is the text being displayed on the legend. If you wanted to instead use labels A, B, and C, you would replace 1:nfd with c("A", "B", "C").
Related
Add labels in dendogram in R
I am trying to apply Hierarchical Clustering for Time Series in order to identify the states with similar behaviors in the time series for residential_percent_change_from_baseline. I get the dendrogram but the index i get in the x axis are just numbers and I want the states names. my data looks like this: Data And this is some part of my code data <- dataset #Convert to factor cols <- c("country_region_code", "country_region", "sub_region_1", "iso_3166_2_code") data[cols] <- lapply(data[cols], factor) sapply(data, class) data$date <- as.Date(data$date) summary(data) #Data preparation n <- 10 s <- sample(1:100, n) i <- c(s,0+s, 279+s, 556+s, 833+s, 1110+s, 1387+s, 1664+s, 1941+s, 2218+s, 2495+s, 2772+s, 3049+s, 3326+s, 3603+s, 3880+s, 4157+s, 4434+s, 4711+s, 4988+s, 5265+s, 5542+s, 5819+s, 6096+s, 6373+s, 6650+s, 6927+s, 7204+s, 7481+s, 7758+s, 8035+s, 8312+s, 8589+s, 8866+s) d <- data[i,3:4] d$residential <- data[i,11] d[,2] =NULL str(d) pattern <- c(rep('Mexico', n), rep('Aguascalientes', n), rep('Baja California',n), rep('Baja California Sur',n), rep('Campeche',n), rep('Coahuila',n), rep('Colima',n), rep('Chiapas',n), rep('Chihuahua',n), rep('Durango',n), rep('Guanajuato',n), rep('Guerrero',n), rep('Hidalgo',n), rep('Jalisco',n), rep('México City',n), rep('Michoacan',n), rep('Morelos',n), rep('Nayarit',n), rep('Nuevo León',n), rep('Oaxaca',n), rep('Puebla',n), rep('Querétaro',n), rep('Quintana Roo',n), rep('San Luis Potosí',n), rep('Sinaloa',n), rep('Sonora',n), rep('Tabasco',n), rep('Tamaulipas',n), rep('Tlaxcala',n), rep('Veracruz',n), rep('Yucatán',n), rep('Zacatecas.',n)) d <- data.matrix(d) distance <- dist(d, method = 'euclidean') hc <- hclust(distance, method="ward.D") plot(hc, cex=.7, hang = -1, col='blue', labels=pattern) I get this dendrogram when I don't specify labels dendrogram with numeric labels But when I do I get this error Error in graphics:::plotHclust(n1, merge, height, order(x$order), hang, : invalid dendrogram input I hope somebody can help me, I am little bit tired of this
Maybe it will work with an alternative to the base r plot function. Try ggdendroplot. It should display the labels on the axis. You will need ggplot2 for this. devtools::install("nicolash2/ggdendroplot") library(ggdendroplot) library(ggplot2) ggplot() + geom_dendro(hc) If you want to modify it (turn it, color it, etc.) check out the github page: https://github.com/NicolasH2/ggdendroplot
Colors per factor-level in plotly
A client wants me to make a plot like this. This reference uses the rgl-package, but the quality of the exported figures is too low. Thus, I started in plotly. I can manage most of the things I want to do, but for some reason, all the bars are in different colors. A MWE: X<-1:60 Y<-sort(runif(60,-3,3)) Z<-runif(60,0,50) p<-plot_ly(x = c(X[1],X[1]+1,X[1]+1,X[1]), y = c(0,0,Y[1],Y[1]), z=c(0,0,0,0),type = "mesh3d",color=I("red")) for(i in X){p<-add_trace(p,x = c(i,i+1,i+1,i), y = c(0,0,Y[i],Y[i]), z=c(0,0,0,0),type = "mesh3d",color=I("red"))} for(i in X){p<-add_trace(p,x = c(i,i+1,i+1,i), y = c(0,0,0,0), z=c(0,0,Z[i],Z[i]),type = "mesh3d",i=c(0,0), j=c(1,2),k=c(2,3),color=I("black"))} p While I would expect something in red and black, I get this multicolored result: What I'm actually looking for is something like the following, with a color for each factor level, but for now, the result is identical to the one above: X<-1:60 Y<-sort(runif(60,-3,3)) Z<-runif(60,0,50) ColFactor<-sample(c(0,1),60,replace = TRUE) p<-plot_ly(x = c(X[1],X[1]+1,X[1]+1,X[1]), y = c(0,0,Y[1],Y[1]), z=c(0,0,0,0), type = "mesh3d",color=ColFactor,colors=c("red","blue")) for(i in X){p<-add_trace(p,x = c(i,i+1,i+1,i), y = c(0,0,Y[i],Y[i]), z=c(0,0,0,0), type = "mesh3d",color=ColFactor,colors=c("red","blue"))} for(i in X){p<-add_trace(p,x = c(i,i+1,i+1,i), y = c(0,0,0,0), z=c(0,0,Z[i],Z[i]), type = "mesh3d",i=c(0,0),j=c(1,2),k=c(2,3),color=I("black"))} p
It seems there is some kind of issue when using plot_ly the way you intend to do. However, there is a workaround (https://github.com/ropensci/plotly/issues/413). To make things work you have to overriden the default values provided by plot_ly by mean of the plotly_build function. The following code should work to obtain a plot where horizontal and vertical bars have different color: X<-1:60 Y<-sort(runif(60,-3,3)) Z<-runif(60,0,50) ColFactor<-sample(c(0,1),60,replace = TRUE) p<-plot_ly(color=I("black")) #This plot a layout where to add the traces and adds #the attribute color needed when overriding default. If it isn't included it doesn't work #Which color you use here is unimportant, it will be override #next lines add the bars, if you plot the result will be the same that you already know for(i in X){p<-add_trace(p,x = c(i,i+1,i+1,i), y = c(0,0,Y[i],Y[i]), z=c(0,0,0,0),type = "mesh3d")} for(i in X){p<-add_trace(p,x = c(i,i+1,i+1,i), y = c(0,0,0,0), z=c(0,0,Z[i],Z[i]),type = "mesh3d",i=c(0,0), j=c(1,2),k=c(2,3))} #next step: override the defaults options using plotly_build() p.optionslist<-plotly_build(p) #you have to change every trace individually that's what the for loop is #horizontal bars for(j in 1:((length(p.optionslist$x$data))/2)){ p.optionslist$x$data[[j]]$color=toRGB("red") } #horizontal vertical bars for(j in (((length(p.optionslist$x$data)/2)+1):length(p.optionslist$x$data))){ p.optionslist$x$data[[j]]$color=toRGB("blue") } #The plot p.optionslist Regarding the use of a ColFactor the following code works (surely there is a better way but I don't know which one) #overriding color option according to the value of ColFactor p.optionslist2<-plotly_build(p) for(j in 1:((length(p.optionslist2$x$data))/2)){ if(ColFactor[j]==1){ p.optionslist2$x$data[[j]]$color=toRGB("red") }else{ p.optionslist2$x$data[[j]]$color=toRGB("blue") } } for(j in (((length(p.optionslist2$x$data))/2)+1):length(p.optionslist2$x$data)){ i=j-length(ColFactor) if(ColFactor[i]==1){ p.optionslist2$x$data[[j]]$color=toRGB("red") }else{ p.optionslist2$x$data[[j]]$color=toRGB("blue") } } #The plot with color by p.optionslist2 If you want the vertical bars all in black and the horizontal bars by factor then you only have to combine both options: p.optionslist3<-plotly_build(p) for(j in 1:((length(p.optionslist3$x$data))/2)){ if(ColFactor[j]==1){ p.optionslist3$x$data[[j]]$color=toRGB("red") }else{ p.optionslist3$x$data[[j]]$color=toRGB("blue") } } for(j in (((length(p.optionslist3$x$data))/2)+1):length(p.optionslist3$x$data)){ p.optionslist3$x$data[[j]]$color=toRGB("black") } #The plot with color by p.optionslist3 Hope it helps you!
Use math symbols in panel titles for stratigraphic plot
I want to include math symbols in the panel titles for this stratigraphic plot: library(analogue) data(V12.122) Depths <- as.numeric(rownames(V12.122)) names(V12.122) (plt <- Stratiplot(Depths ~ O.univ + G.ruber + G.tenel + G.pacR, data = V12.122, type = c("h","l","g"), zones = 400)) plt For example, I want to have this text in place of "O.univ" etc.: I used this code to make that text: plot(1, type="n", axes=FALSE, ann=FALSE) title(line = -1, main = expression(phantom()^14*C~years~BP)) title(line = -3, main = expression(delta^18*O)) title(line = -5, main = expression(paste("TP ", mu,"g l"^-1))) title(line = -10, main = expression("very long title \n with \n line breaks")) But if I try to update the colnames of the data frame passed to Stratiplot, the code is not parsed, and we do not get the correct text formatting: V12.122 <- V12.122[, 1:4] names(V12.122)[1] <- expression(phantom()^14*C~years~BP) names(V12.122)[2] <- expression(delta^18*O) names(V12.122)[3] <- expression(paste("TP ", mu,"g l"^-1)) (plt <- Stratiplot(Depths ~ ., data = V12.122, type = c("h","l","g"), zones = 400)) plt How can I get Stratiplot to parse the expressions in the colnames and format them correctly in the plot? I've tried looking through str(plt) to see where the panel titles are stored, but no success: text <- expression(phantom()^14*C~years~BP) plt$condlevels$ind[1] <- text names(plt$packet.sizes)[1] <- text names(plt$par.settings$layout.widths$panel)[1] <- text
You can't actually do this in the current release of analogue; the function is doing too much messing around with data for the expressions to remain unevaluated prior to plotting. I could probably figure this out to allow expressions as the names of the data argument object, but it is easier to just allow users to pass a vector of labels that they want for the variables. This is now implemented in the development version of the package on github, and I'll push this to CRAN early next week. This change implements a new argument labelValues which takes a vector of labels for use in labelling the top axis. This can be a vector of expressions. Here is an illustration of the usage: library("analogue") set.seed(1) df <- setNames(data.frame(matrix(rnorm(200 * 3), ncol = 3)), c("d13C", "d15N", "d18O")) df <- transform(df, Age = 1:200) exprs <- expression(delta^{13}*C, # label for 1st variable delta^{15}*N, # label for 2nd variable delta^{18}*O) # label for 3rd variable Stratiplot(Age ~ ., data = df, labelValues = exprs, varTypes = "absolute", type = "h") which produces Note that this is just a first pass; I'm pretty sure I haven't accounted for any reordering that goes on with sort and svar etc. if they are used.
Never used lattice plots, but I thought a chance to learn something should be worth while. Took too long to figure out. text <- "c( expression(phantom()^14*C~years~BP),expression(delta^18*O))" strip = strip.custom(factor.levels=eval(parse(text=text))) plt <- Stratiplot(Depths ~ ., data = V12.122[, 1:4], type = c("h","l","g"), zones = 400, strip = strip) Hope this gets you started.
Adding axis titles in gplot using filled.contour in R
This is my reproducible code example. Everything looks as it should in the graph, except the axis titles/labels are not being added. I am really struggling to figure out how to fix it, despite following the directions in the function documentation. Help will be much appreciated - thanks in advance. output <- matrix(data = c(0.7,0.5,0.3,0.8,0.6,0.4,0.9,0.7,0.5,1,0.8,0.6),nrow=3, ncol=4) # Change column names colnames(output) <- c(10,20,30,40) # Change row names rownames(output) <- c(1,2,3) library(gplots) matrix.axes <- function(data) { # Do the rows, las=2 for text perpendicular to the axis x <- (1:dim(data)[1] - 1) / (dim(data)[1] - 1); axis(side=1, at=x, labels=rownames(data), las=1); # Do the columns x <- (1:dim(data)[2] - 1) / (dim(data)[2] - 1); axis(side=2, at=x, labels=colnames(data), las=2); } # Not necessary to save as pdf unless this is part of the problem # save to pdf # pdf("C:/Test.pdf") # Plot results filled.contour(output,plot.title=title(main="Method"), xlab='Case number',ylab='Sample number', plot.axes=matrix.axes(output)) # dev.off()
Your xlab = and ylab = need to be inside the plot.title() function: filled.contour(output, plot.title = title(main = "Method", xlab='Case number', ylab='Sample number'), plot.axes = matrix.axes(output))
Legend in multiple plot in R
According to the comments from others, this post has been separated into several smaller questions from the previous version of this OP. In the graph below, will you help me to (Newbie to R) Custom legends according to the data they represent like filled for variable 1, circle points for variable 2 and line for variable 3 and their colors. same letter size for the legend and axis-names. The graph below is produced with the data in pdf device with following layout. m <- matrix(c(1,2,3,3,4,5),nrow = 3,ncol = 2,byrow = TRUE) layout(mat = m,heights = c(0.47,0.06,0.47)) par(mar=c(4,4.2,3,4.2)) #Codes for Fig A and B ... #Margin for legend par(mar = c(0.2,0.2,0.1,0.1)) # Code for legend ... #Codes for Fig C and D ...
Using doubleYScale from latticeExtra and the data in the long format (see my previous answer), you can simplify the work: No need to create a custom layout to superpose many plots No need to create the legend manually The idea is to create 2 separates objects and then merge them using doubleYScale. The latter will create the second axes. I hope I get your ploygon idea since it is not very clear why do you invert it in your OP. library(latticeExtra) obj1 <- xyplot(Variable~TimeVariable|Type,type='l', groups=time, scales=list(x=list(relation='free'), y=list(relation='free')), auto.key=list(columns = 3,lines = TRUE,points=FALSE) , data = subset(dat.l,time !=1)) obj2 <- xyplot(Variable~TimeVariable|Type, data = subset(dat.l,time ==1),type='l', scales=list(x=list(alternating=2), auto.key=list(columns = 3,lines = TRUE,points=FALSE), y=list(relation='free')), panel=function(x,y,...){ panel.xyplot(x,y,...) panel.polygon(x,y,col='violetred4',border=NA,alpha=0.3) }) doubleYScale(obj1, obj2, add.axis = TRUE,style1 = 0, style2 = 1)
Try the following: 1) For the legend part The data can be found on https://www.dropbox.com/s/4kgq8tyvuvq22ym/stackfig1_2.csv The code I used is as follows: data <- read.csv("stackfig1_2.csv") library(Hmisc) label1=c(0,100,200,300) plot(data$TimeVariable2C,data$Variable2C,axes=FALSE,ylab="",xlab="",xlim=c(0,24), ylim=c(0,2.4),xaxs="i",yaxs="i",pch=19) lines(data$TimeVariable3C,data$Variable3C) axis(2,tick=T,at=seq(0.0,2.4,by=0.6),label= seq(0.0,2.4,by=0.6)) axis(1,tick=T,at=seq(0,24,by=6),label=seq(0,24,by=6)) mtext("(C)",side=1,outer=F,line=-10,adj=0.8) minor.tick(nx=5,ny=5) par(new=TRUE) plot(data$TimeVariable1C,data$Variable1C,axes=FALSE,xlab="",ylab="",type="l", ylim=c(800,0),xaxs="i",yaxs="i") axis(3,xlim=c(0,24),tick=TRUE,at= seq(0,24,by=6),label=seq(0,24,by=6),col.axis="violetred4",col="violetred4") axis(4,tick=TRUE,at= label1,label=label1,col.axis="violetred4",col="violetred4") polygon(data$TimeVariable1C,data$Variable1C,col='violetred4',border=NA) legend("top", legend = c("Variable A","Variable B","Variable C"), col = c("black","violetred4","black"), ncol = 2, lwd =c("","",2),pch=c(19,15,NA),cex=1) The output is as follows: 2) To make the font size same use the parameter cex and make it same everywhere.