How to wrap long titles in lattice graphics in R? - r

I need to add a long title to a graphic created with the likert function from the HH package, that uses lattice, but it (lattice) doesn't have this facility. Is there a way to do this?
My code:
library(HH)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)
for(i in 1:2){
plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
main=list(label = items[i,], cex=1.2), xlab=list(label="Percent", cex=1.1),
ylab="", ylab.right = list("Subjects per group", cex=1.1),
scales = list(y = list(relation = "free", labels=""), cex=1.1),
layout = c(1, 2), auto.key=list(space="bottom", columns=3, title="", cex=1.1))
print(plot_obj)
}
dev.off()
My data:
ssb <- structure(list(`Strongly Disagree` = c(2L, 1L), `Moderate Disagree` = 1:2,
`Slightly Disagree` = c(3L, 1L), `Slightly Agree` = c(1L,
5L), `Moderate Agree` = 4:5, `Strongly Agree` = c(9L, 6L),
Grup = c("Experimental grup", "Control grup")), .Names = c("Strongly Disagree",
"Moderate Disagree", "Slightly Disagree", "Slightly Agree", "Moderate Agree",
"Strongly Agree", "Grup"), row.names = c("1", "2"), class = "data.frame")
Title items:
items <- structure(list(V1 = structure(1:2, .Label = c("1. În cele mai multe privinţe, viaţa mea corespunde idealului meu.",
"2. Până în prezent am primit cele mai importante lucruri pe care le doresc în viață."
), class = "factor")), .Names = "V1", class = "data.frame", row.names = c(NA,
-2L))
UPDATE
Graphic titles are not added directly, but dynamically, from a data frame, and the data frame are loaded from a .csv file. If, as was suggested in comments, I add a \n to the long title in the .csv file this doesn't work.

I solved my problem, thanks to #josh-obrien. Now, when the graphic title is longer than 70 characters it is wrapped to 65 characters wide version.
library(HH)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)
for(i in 1:2){
if(stri_length(items[i,])>70){
graphic.title <- paste(strwrap(items[i,], width = 65), collapse="\n")
} else {
graphic.title <- items[i,]
}
plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
main=list(label = graphic.title, cex=1.2), xlab=list(label="Percent", cex=1.1),
ylab="", ylab.right = list("Subjects per group", cex=1.1),
scales = list(y = list(relation = "free", labels=""), cex=1.1),
layout = c(1, 2), auto.key=list(space="bottom", columns=3, title="", cex=1.1))
print(plot_obj)
}
dev.off()

Related

How do I change the shape of the lines in a plot generated by a for loop?

I'm not sure how to change the shape and color of the for loop for data in a df, fish
structure(list(Region = structure(c(7L, 7L, 7L, 7L, 7L), .Label = c("American Samoa",
"Johnston Atoll", "Line Islands", "MHI", "Musicians Seamounts",
"Northern Marianas", "NWHI", "Southern Marianas", "Tokelau Ridge",
"Wake Island"), class = "factor"), ObservationYear = c(2015,
2015, 2015, 2015, 2015), `Mega-Habitat` = c("bank", "bank", "tablemount",
"bank", "atoll"), Total_fish = c(6, 10, 21, 11, 7), Lat = c(23.2227305,
25.0840027, 26.8267143809524, 26.8188378, 27.5178584285714),
Long = c(-163.516748333333, -172.490419, -175.607307619048,
-176.315991, -175.460592857143), Temperature = c(1.82256666666667,
2.00518, 3.03555714285714, 2.01533, 1.5475), Salinity = c(34.64115,
34.61702, 34.4760619047619, 34.61106, 34.6673857142857),
Oxygen = c(3.16008333333333, 2.79735, 1.27077619047619, 2.58692,
3.73167142857143), Distance = c(350, 960, 1130, 360, 460),
`CTD Availability` = c(NA_character_, NA_character_, NA_character_,
NA_character_, NA_character_), depth_bin = c("2000-3000",
"1000-2000", "1000-2000", "1000-2000", "2000-3000"), EventID = c("D2-EX1504L2-01",
"D2-EX1504L2-06", "D2-EX1504L2-08", "D2-EX1504L2-10", "D2-EX1504L2-12"
), Average_Depth = c(2160.20383333333, 1880.4596, 1217.94385,
1890.1868, 2780.92557142857), POC_Flux = c(2.56732258067581,
2.86961424536357, 3.38129564627503, 3.38129564627503, 3.80216410589398
)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
I ran a GAM before the loop:
g1 = mgcv::gam(Total_fish ~ s(Average_Depth, by = Region) + Region + offset(log(Distance)), data =fish,family= nb)
I tried defining shapes, but it did not work
shapes= c(0,1,2,3,4,5,6,7,8,9,10)
shapes <-shapes[as.numeric(fish$Region)]
colors.use = rainbow(nlevels(fish$Region))
for (i in 1:nlevels(fish$Region)) {
predictions = predict(g1, type="response", newdata = data.frame(Distance= 1000, Average_Depth = seq(0,3000,length=1000), Region = levels(fish$Region)[i]))
if (i == 1) plot(xlab= "Depth (m)", ylab = "fish/1000 m",seq(0,3000,length=1000), predictions, type = 'l', col=colors.use[i], pch=i)
if (i > 1) lines(seq(0,3000,length=1000), predictions,col=colors.use[i],pch=i)
}
I just need to be able to differentiate between the regions and the current rainbow colors alone are not very useful for that

How to add labels as percentages to the lattice stacked bar charts in R?

I have created some stacked bar charts with the likert function from the HH package, that uses lattice. Now I want to add labels represented as percentages inside to each segment of the charts, or, better, only to that segments that have a sufficient width for that. How to do this? I mention that my data are represented as frequencies, not as percentages.
My data:
ssb <- structure(list(`Strongly Disagree` = c(2L, 1L), `Moderate Disagree` = 1:2,
`Slightly Disagree` = c(3L, 1L), `Slightly Agree` = c(1L,
5L), `Moderate Agree` = 4:5, `Strongly Agree` = c(9L, 6L),
Grup = c("Experimental grup", "Control grup")), .Names = c("Strongly Disagree",
"Moderate Disagree", "Slightly Disagree", "Slightly Agree", "Moderate Agree",
"Strongly Agree", "Grup"), row.names = c("1", "2"), class = "data.frame")
My code:
library(HH)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)
plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
main="", xlab=list(label="Percent", cex=1.1),
ylab="", ylab.right = list("Subjects per group", cex=1.1),
scales = list(y = list(relation = "free", labels=""), cex=1.1),
layout = c(1, 2), auto.key=list(space="bottom", columns=3, title="", cex=1.1))
print(plot_obj)
dev.off()
Thanks to Deepayan Sarkar, this question was solved:
library(HH)
library(latticeExtra)
ppi <- 150
jpeg("ssb_%02d.jpg", width=7*ppi, height=4*ppi, res=ppi)
plot_obj <- likert(Grup ~ . | Grup, data = ssb, as.percent = TRUE, positive.order = TRUE,
main="", xlab=list(label="Percent", cex=1.1),
ylab="", ylab.right = list("Subjects per group", cex=1.1),
scales = list(y = list(relation = "free", labels=""), cex=1.1),
layout = c(1, 2), auto.key=list(space="bottom", columns=3, title="", cex=1.1))
plot_obj <- plot_obj +
layer({
id = which(x > 0)
xx = 0.5 * (cumsum(x[id]) + cumsum(c(0, x[id][-length(id)])))
panel.text(xx, y[id], labels = paste(x[id], "%", sep = ""))
id = which(x < 0)
xx = 0.5 * (cumsum(x[id]) + cumsum(c(0, x[id][-length(id)])))
panel.text(xx, y[id], labels = paste(-x[id], "%", sep = ""))
})
print(plot_obj)
dev.off()

Line plot with factor variables in R

How can I make R draw lines between two observations according with factor variables?
I have two 'time' points, early and late, coded as categorical
plotdata <- structure(list(
x = structure(1:2, .Label = c("early", "late"), class = "factor"),
y = 1:2
),
.Names = c("x", "y"), row.names = c(NA, -2L), class = "data.frame"
)
I only get kind of a bar plot:
plot(plotdata)
I also tried coding the variables as 0 and 1, but then I get a continuous axis with.
Let's say your data is
d <- structure(list(x = structure(1:2, .Label = c("early", "late"), class = "factor"),
y = 1:2), .Names = c("x", "y"), row.names = c(NA, -2L), class = "data.frame")
d
# x y
# early 1
# late 2
With base R
plot(as.numeric(d$x), d$y, type = "l", xaxt = "n")
axis(1, labels = as.character(d$x), at = as.numeric(d$x))
With ggplot2
library(ggplot2)
ggplot(d, aes(x = x, y = y)) + geom_line(aes(group = 1))

Plotting confidence intervals data with R

I would like to plot mean CPUE by year and add in CIs that are already calculated.
The CIs are calculated following an approach for trawl survey data so I do not think I can use any of the CI plot functions available in R. I would really appreciate any help.
I have been trying to figure this out following examples I found online, but the CIs are not being plotted on my data points. I have R version 3.1.0 on windows 8. This is my code.
dput(fall)
structure(list(Year = structure(1:7, .Label = c("2007", "2008",
"2009", "2010", "2011", "2012", "2013", "2014"), class = "factor"),
Season = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Fall",
"Spring"), class = "factor"), CPUE = c(2.67597320766895,
1.13720423803133, 3.33880765324431, 0.806172684858967, 1.4489759307485,
10.5492990950043, 4.52479039663784), Variance = c(6.80824504958873,
0.320707030421567, 11.5769406857122, 1.05791053306542, 0.187046436602381,
15.8421823978692, 2.68384838783695), SD = c(2.60926139924476,
0.566310012644635, 3.40249036526369, 1.0285477786984, 0.432488654882855,
3.98022391303168, 1.63824552123207), Number = c(75, 91, 87,
85, 115, 157, 208), CV = c(0.975070076100538, 0.497984437364567,
1.01907348929115, 1.27584052153583, 0.298478839920718, 0.377297475139038,
0.362059980159386), lower = c(2.07563668109912, 1.01926446969017,
2.61363856286983, 0.584320068914576, 1.36908295705723, 9.92183627713643,
4.30084507885747), upper = c(3.27630973423878, 1.2551440063725,
4.06397674361879, 1.02802530080336, 1.52886890443977, 11.1767619128722,
4.7487357144182)), .Names = c("Year", "Season", "CPUE", "Variance",
"SD", "Number", "CV", "lower", "upper"), row.names = c(NA, 7L
), class = "data.frame")
My plot attempt was:
plot(fall$CPUE, type='n', xlab="Year", ylab='Mean CPUE', axes=F)
axis(1, at=1:8, labels=levels(fall$Year))
axis(2)
box()
lines(fall$Year, fall$CPUE, col=1)
points(fall$Year, fall$CPUE, col=1, pch=16)
arrows(y0 = fall$lower, y1 = fall$upper, x0 = fall$CPUE, x1 = fall$CPUE,
length=0.1, code = 3, col = 4, angle = 90)
Andre's answer here helped me to find a solution.
Data for plot
structure(list(CPUE = c(2.67597320766895, 1.13720423803133, 3.33880765324431, 0.806172684858967, 1.4489759307485, 10.5492990950043, 4.52479039663784 ), lower = c(2.25499288520513, 1.04583532734779, 2.80755247046762, 0.640225963050555, 1.37919786502951, 9.90712658332295, 4.26047455308042 ), upper = c(3.09695353013276, 1.22857314871488, 3.870062836021, 0.972119406667378, 1.51875399646749, 11.1914716066857, 4.78910624019525 )), .Names = c("CPUE", "lower", "upper"), class = "data.frame", row.names = c(NA, 7L))
Plot
plot(fall$CPUE, type='l', xlab="Year", ylab='Mean CPUE', axes=F,ylim=c(0,12))
axis(1, at=1:8, labels=levels(fall$Year))
axis(2)
box()
require(plotrix)
plotCI(fall$CPUE,y=NULL,uiw = fall$upper-fall$CPUE,ui=NULL,li=NULL,err="y", sfrac=0.01,gap=0,slty=par("lty"),add=T,scol="black",pch=18,pt.bg=par("bg"))

error : ggplot2 doesn't know how to deal with data of class uneval

I have this code
ggplot() +
stat_density(kernel = "biweight",aes(x=fd, colour=id), data=foo1,position="identity",geom="line")+
coord_cartesian(xlim = c(0, 200))+
xlab("Flood Duration")+
ylab("Density")+
ggtitle("PDFs of Flood Duration")+
ggsave("pdf_fd_conus.png")
And I wrote this function
pdf.plot<-function(data,x,xl,yl,title,save){
ggplot() +
stat_density(data, kernel = "biweight",aes_string(x=x, colour='id'),
position="identity",geom="line")+
coord_cartesian(xlim = c(0, 200))+
xlab(xl)+
ylab(yl)+
ggtitle(title)+
ggsave(save)
}
Calling using this:
pdf.plot(data=foo1,x='fd',xl='b',
yl='a',title='a',save='y.png')
But I am getting this error:
Error: ggplot2 doesn't know how to deal with data of class uneval
Called from: eval(expr, envir, enclos)
This is dput(head(foo1,4))
structure(list(id = structure(c(1L, 1L, 1L, 1L), .Label = c("dfa",
"dfb", "cfa", "csb", "bsk"), class = "factor"), lon = c(-70.978611,
-70.978611, -70.945278, -70.945278), lat = c(42.220833, 42.220833,
42.190278, 42.190278), peakq = c(14.7531, 17.3865, 3.3414, 2.7751
), area = c(74.3327, 74.3327, 11.6549, 11.6549), fd = c(29, 54.75,
23, 1), tp = c(14.25, 19.75, 13.5, 0.5), rt = c(14.75, 35, 9.5,
0.5), bl = c(15485.3, 15485.3, 8242.64, 8242.64), el = c(0.643551,
0.643551, 0.474219, 0.474219), k = c(0.325279, 0.325279, 0.176624,
0.176624), r = c(81.947, 81.947, 38.7003, 38.7003), si = c(0.0037157,
0.0037157, -9999, -9999), rr = c(0.00529193, 0.00529193, 0.00469513,
0.00469513)), .Names = c("id", "lon", "lat", "peakq", "area",
"fd", "tp", "rt", "bl", "el", "k", "r", "si", "rr"), row.names = c(NA,
4L), class = "data.frame")
Could you please help?
Your problem is that you didn't specify what argument data is in stat_density. If you look at ?stat_density you'll see the first implied argument is actually mapping=. You need to change pdf.plot to:
pdf.plot<-function(data,x,xl,yl,title,save){
ggplot() +
stat_density(data = data, kernel = "biweight",aes_string(x=x, colour='id'),
position="identity",geom="line")+
coord_cartesian(xlim = c(0, 200))+
xlab(xl)+
ylab(yl)+
ggtitle(title)+
ggsave(save)
}

Resources