How do I get multiple subplot in rcharts? - r

I have two lines as code below need layout in two row, how to do it in rcharts?
h1 <- Highcharts$new()
h1$chart(type = "line")
h1$series(data = c(1, 3, 2, 4, 5, 4, 6, 2, 3, 5, NA), dashStyle = "longdash")
h1$series(data = c(NA, 4, 1, 3, 4, 2, 9, 1, 2, 3, 4), dashStyle = "shortdot")
h1$legend(symbolWidth = 80)
h1
enter image description here

Related

How can I change size of y-axis text labels on a likert() object in R?

I'm working with the likert() library to generate nice looking diverging stacked bar charts in R. Most of the formatting has come together, but I can't seem to find a way to shrink the text for the y-axis labels (e.g. "You and your family in the UK", "People in your local area..." etc.) which are too large for the plot. Any ideas here? I'm starting to wonder if I need to revert to ggplot, which will require more code, but have more customisability...
# Ingest data to make reproducible example:
climate_experience_data <- structure(list(Q25_self_and_family = c(4, 2, 3, 5, 3, 3, 4, 2,
4, 2, 4, 4, 3, 3, 2, 5, 3, 4, 1, 3, 3, 2, 4, 2, 2, 2, 4, 3, 3,
3, 2, 5, 5, 4, 2, 2, 2, 3, 1, 3, 2, 1, 2, 4, 2), Q25_local_area = c(3,
3, 3, 5, 3, 2, 4, 2, 4, 2, 4, 3, 2, 3, 2, 5, 4, 5, 1, 4, 3, 3,
4, 2, 3, 2, 3, 3, 2, 3, 2, 5, 5, 2, 2, 2, 2, 3, 1, 1, 2, 1, 2,
4, 3), Q25_uk = c(4, 3, 3, 5, 2, 3, 5, 2, 4, 2, 4, 3, 3, 3, 3,
5, 4, 5, 2, 3, 3, 2, 4, 2, 4, 3, 4, 3, 2, 4, 4, 5, 5, 4, 3, 3,
2, 4, 2, 5, 2, 2, 2, 3, 3), Q25_outside_uk = c(4, 4, 3, 5, 4,
4, 5, 2, 4, 3, 3, 3, 3, 4, 3, 5, 4, 5, 4, 3, 3, 2, 4, 2, 5, 3,
3, 2, 2, 3, 4, 4, 5, 4, 4, 3, 2, 4, 4, 5, 2, 3, 2, 2, 2)), row.names = c(NA,
-45L), class = c("tbl_df", "tbl", "data.frame"))
# load libraries:
require(tidyverse)
require(likert)
# Q25 - generate diverging stacked bar chart using likert()
q25_data <- select(climate_experience_data, Q25_self_and_family:Q25_outside_uk)
names(q25_data) <- c("You and your family in the UK", "People in your local area or city", "The UK as a whole", "Your family and/or friends living outside the UK")
# Set up levels text for question responses
q25_levels <- paste(c("not at all", "somewhat", "moderately", "very", "extremely"),
"serious")
q25_likert_table <- q25_data %>%
mutate(across(everything(),
factor, ordered = TRUE, levels = 1:5, labels=q25_levels)) %>%
as.data.frame %>%
# make plot:
plot(q25_likert_table, wrap=20, text.size=3, ordered=FALSE, low.color='#B18839', high.color='#590048') +
ggtitle(title) +
labs(title = "How serious a threat do you think \nclimate change poses to the following?", y="") +
guides(fill = guide_legend(title = NULL)) +
theme_ipsum_rc() +
theme()
Here's a sample of output:
As your plot is still a ggplot object you could adjust the size of the y axis labels via theme(axis.text.y = ...):
library(tidyverse)
library(likert)
library(hrbrthemes)
q25_likert_table <- q25_data %>%
mutate(across(everything(),
factor,
ordered = TRUE, levels = 1:5, labels = q25_levels
)) %>%
as.data.frame() %>%
likert()
plot(q25_likert_table, wrap = 20, text.size = 3, ordered = FALSE, low.color = "#B18839", high.color = "#590048") +
ggtitle(title) +
labs(title = "How serious a threat do you think \nclimate change poses to the following?", y = "") +
guides(fill = guide_legend(title = NULL)) +
theme_ipsum_rc() +
theme(axis.text.y = element_text(size = 4))

Nodes sliding off path diagram in R

This is a sample dput since the dataset is huge:
> dput(head(dat, n=20))
structure(list(q01 = c(2, 1, 2, 3, 2, 2, 2, 2, 3, 2, 2, 2, 3,
2, 2, 3, 1, 2, 2, 2), q02 = c(1, 1, 3, 1, 1, 1, 3, 2, 3, 4, 1,
1, 1, 2, 2, 1, 2, 2, 3, 1), q03 = c(4, 4, 2, 1, 3, 3, 3, 3, 1,
4, 5, 3, 3, 1, 3, 2, 5, 3, 4, 1), q04 = c(2, 3, 2, 4, 2, 2, 2,
2, 4, 3, 2, 3, 4, 2, 4, 2, 2, 3, 2, 2), q05 = c(2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 3, 2, 5), q21 = c(2,
4, 3, 4, 2, 3, 2, 2, 5, 2, 2, 3, 4, 5, 4, 2, 1, 3, 2, 5), q22 = c(2,
4, 2, 4, 4, 1, 4, 4, 3, 4, 5, 4, 3, 3, 4, 3, 4, 3, 4, 5), q23 = c(5,
2, 2, 3, 4, 4, 4, 4, 3, 4, 5, 4, 4, 1, 4, 4, 4, 4, 4, 5)), variable.labels = c(q01 = "Statistics makes me cry",
q02 = "My friends will think I'm stupid for not being able to cope with SPSS",
q03 = "Standard deviations excite me", q04 = "I dream that Pearson is attacking me with correlation coefficients",
q05 = "I don't understand statistics", q06 = "I have little experience of computers",
q07 = "All computers hate me", q08 = "I have never been good at mathematics",
q09 = "My friends are better at statistics than me", q10 = "Computers are useful only for playing games ",
q11 = "I did badly at mathematics at school", q12 = "People try to tell you that SPSS makes statistics easier to understand but it doesn't",
q13 = "I worry that I will cause irreparable damage because of my incompetenece with computers",
q14 = "Computers have minds of their own and deliberately go wrong whenever I use them",
q15 = "Computers are out to get me", q16 = "I weep openly at the mention of central tendency",
q17 = "I slip into a coma whenever I see an equation", q18 = "SPSS always crashes when I try to use it",
q19 = "Everybody looks at me when I use SPSS", q20 = "I can't sleep for thoughts of eigen vectors",
q21 = "I wake up under my duvet thinking that I am trapped under a normal distribtion",
q22 = "My friends are better at SPSS than I am", q23 = "If I'm good at statistics my friends will think I'm a nerd"
), codepage = 65001L, row.names = c(NA, 20L), class = "data.frame")
I mostly copied another semPath model but edited it to fit the dataset I was using. First the nodes:
nodeNames <- c(
"Statistics makes me cry.",
"My friends think I'm stupid for not being able to cope with SPSS.",
"Standard deviations excite me.",
"I dream that Pearson is attacking me with correlation coefficients.",
"I don't understand statistics.",
"I have little experience with computers.",
"All computers hate me.",
"I've never been good at mathematics.",
"SPSS Anxiety"
)
Then the actual semPath:
semPaths(onefac8items_a,
what = "std", # this argument controls what the color of edges represent. In this case, standardized parameters
whatLabels = "est",
style = "lisrel",
residScale = 8,
theme = "colorblind",
manifests = paste0("q",1:8),
nCharNodes = 0,
reorder = FALSE,
nodeNames = nodeNames,
legend.cex = 0.5,
rotation = 2,
layout = "tree2",
cardinal = "lat cov",
curvePivot = TRUE,
sizeMan = 4,
sizeLat = 10,
mar = c(2,5,2,5.5),
filetype = "pdf", width = 8, height = 6, filename = "SPSS Anxiety"
)
So I really only have one question here. When I try to run my path diagram, the nodes look like they are sliding off to the right of the page. How do I fix this? Below is a picture of what I'm referring to:
Since you didn't share your model, I reproduced a dummy model. It seems semPaths doesn't allow us to adjust nodeNames, maybe you could save this graph as an object and try to reproduce with the "plot()" function in order to rescaling since semPaths has a lot of attributes.
semPaths(fit,
what = "std",
style = "lisrel",
residScale = 8,
theme = "colorblind",
nCharNodes = 4,
reorder = FALSE,
nodeNames = nodeNames,
legend.cex = 0.35,
rotation = 2,
layout = "tree2",
cardinal = "lat cov",
curvePivot = TRUE)
Or we could change the GLRatio in the plotOptions:
a<-semPaths(onefac8items_a,
what = "std",
whatLabels = "est",
style = "lisrel",
residScale = 8,
theme = "colorblind",
nCharNodes = 0,
reorder = FALSE,
nodeNames = nodeNames,
legend.cex = 0.5,
rotation = 2,
layout = "tree2",
cardinal = "lat cov",
curvePivot = TRUE,
sizeMan = 4,
sizeLat = 10,
mar = c(2,5,2,5.5)
)
a$plotOptions$GLratio<-1 # you may need to play with this number
plot(a)
I ended up just shortening my questions down in the nodes and it fixed the problem. I guess there's a limit to how much text you can put into your legend:
nodeNames <- c(
"Statistics makes me cry.",
"Friends think I'm stupid because I cant do SPSS.",
"Standard deviations excite me.",
"I dream that Pearson is attacking me with correlations.",
"I don't understand statistics.",
"I have little experience with computers.",
"All computers hate me.",
"I've never been good at mathematics.",
"SPSS Anxiety"
)
Your page isn't big enough.
There are two graphics systems in R, base and grid. The one semPaths uses is the base package which sort of mimics how you draw on a paper: first you set up the size, then you draw things; you can't go back. The other, grid, is used in lattice and ggplot2 which saves the plotting until you call for it. grid plots typically do not run off the page as base graphics can, the plots are usually scaled to fit with the plotting region.
Here is basically your problem using an example from lavaan::cfa
library('lavaan')
library('semPlot')
nodeNames <- c(
"Statistics makes me cry.",
"My friends think I'm stupid for not being able to cope with SPSS.",
"Standard deviations excite me.",
"I dream that Pearson is attacking me with correlation coefficients.",
"I don't understand statistics.",
"I have little experience with computers.",
"All computers hate me.",
"I've never been good at mathematics.",
"SPSS Anxiety"
)
?semPlot::semPaths
example(cfa)
semPaths(
fit,
what = "std", # this argument controls what the color of edges represent. In this case, standardized parameters
whatLabels = "est",
style = "lisrel",
residScale = 8,
theme = "colorblind",
# manifests = paste0("q",1:8),
nCharNodes = 0,
reorder = FALSE,
nodeNames = nodeNames,
legend.cex = 0.5,
rotation = 2,
layout = "tree2",
cardinal = "lat cov",
curvePivot = TRUE,
sizeMan = 4,
sizeLat = 10,
mar = c(2,5,2,5.5),
filetype = "pdf", width = 8, height = 6, filename = "SPSS-Anxiety"
)
I'm not sure what semPaths is doing here with the size because it is definitely not coming out 8x6
$ identify -verbose SPSS-Anxiety.pdf | grep "Print size"
8: Print size: 11.1944x6
I'm guessing it compensates for the extra features to fit everything on, but it is not doing a very good job.
The typical way to save base plots to file is
pdf() ## or png() or jpg() etc
plotting code
dev.off() ## or graphics.off() to close everything not just the current device
And to do this you need to remove the filetype part from your code
pdf('SPSS-Anxiety-2.pdf', width = 8, height = 6)
par(oma = c(0, 2, 0, 25), xpd = NA)
semPaths(
fit,
what = "std", # this argument controls what the color of edges represent. In this case, standardized parameters
whatLabels = "est",
style = "lisrel",
residScale = 8,
theme = "colorblind",
# manifests = paste0("q",1:8),
nCharNodes = 0,
reorder = FALSE,
nodeNames = nodeNames,
legend.cex = 0.5,
rotation = 2,
layout = "tree2",
cardinal = "lat cov",
curvePivot = TRUE,
sizeMan = 4,
sizeLat = 10,
mar = c(2,5,2,5.5)
)
dev.off()
Now I am getting something 8x6
$ identify -verbose SPSS-Anxiety-2.pdf | grep "Print size"
8: Print size: 8x6
I increased the size of the outer margins, oma see ?par, which gives me 2 extra lines of space on the left and 25 on the right. Also, note xpd = NA which turns off clipping, ie, anything printed outside of the plotting area will be shown--this also comes up a lot in base plots.
But this is a lot of wasted space for some text. I would either scale it down or split the text into multiple lines. You can use strwrap to split each label at white space into <= some maximum width:
par(oma = c(0, 0, 3, 0))
semPaths(
fit,
what = "std", # this argument controls what the color of edges represent. In this case, standardized parameters
whatLabels = "est",
style = "lisrel",
residScale = 8,
theme = "colorblind",
# manifests = paste0("q",1:8),
nCharNodes = 0,
reorder = FALSE,
nodeNames = sapply(nodeNames, function(x)
paste(strwrap(x, 30), collapse = '\n ')),
legend.cex = 0.5,
rotation = 2,
layout = "tree2",
cardinal = "lat cov",
curvePivot = TRUE,
sizeMan = 4,
sizeLat = 10,
mar = c(2,5,2,5.5)
)
title('Anxiety and Depression SEM Path Diagram', outer = TRUE)

How to create ggplot graphs with the three groups into one plot?

My codes are:
ggplot(data=df2, aes(x=stress, fill=as.factor(JP_Gender))) + geom_density(alpha=.3)
ggplot(data=df1, aes(x=CGstress)) + geom_density(alpha=.3)
My dataset 1:
structure(list(CGstress = c(4, 1, 10, 8, 9.5, 5, 5, 6, 6, 6,
7, 3, 4.5, 8, 9, 1, 5, 1, 5.5, 4, 1, 7, 9, 8, 3, NA, 10, 9, 5,
3, NA, 10, 6, NA, 10, 7)), row.names = c(NA, -36L), class = c("tbl_df",
"tbl", "data.frame"))
My dataset 2:
structure(list(stress = c(7, 2, 5, 6, 7, 1, 6, 10, 9, 10, 10,
10, 10, 8, 9, 4, 7, 6, 4, 9, 4, 8, 3.5, 7, 6, 6, 1, 7, 9, 8,
10, 6, 3, 1, 1, 1, 9, 6, 4), JP_Gender = structure(c(1, 2, 1,
2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1), label = "What is your gender?", format.stata = "%12.0g", labels = c(Male = 1,
Female = 2, Transgender = 3, Other = 4), class = c("haven_labelled",
"vctrs_vctr", "double"))), row.names = c(NA, -39L), class = c("tbl_df",
"tbl", "data.frame"))
Above codes give me 2 graphs. How to combine 2 graphs into one plot? And how to label the legends?
You can try combining the two datasets and then plot :
library(dplyr)
library(ggplot2)
df1 %>%
mutate(id = 3) %>%
rename(stress = CGstress) %>%
bind_rows(df2 %>%
mutate(id = as.integer(JP_Gender)) %>%
select(stress, id)) %>%
mutate(id = factor(id)) %>%
ggplot(aes(x=stress, fill=factor(id))) + geom_density(alpha=.3)

Add legend to graph in R

For a sample dataframe:
df <- structure(list(antibiotic = c(0.828080341411847, 1.52002304506738,
1.31925434545302, 1.66681722567074, 1.17791610945551, 0.950096368502059,
1.10507733691997, 1.0568193215304, 1.03853131016669, 1.02313195567946,
0.868629787234043, 0.902126485349154, 1.12005679002801, 1.88261441540084,
0.137845900627507, 1.07040656448604, 1.41496470588235, 1.30978543173373,
1.16931780610558, 1.05894439450366, 1.24805122785724, 1.21318238007025,
0.497310305098053, 0.872362356327429, 0.902584749481137, 0.999731895498823,
0.907560340983954, 1.05930840957587, 1.40457554864091, 1.09747179272879,
0.944219456216072, 1.10363111431903, 0.974649273935516, 0.989983064420841,
1.14784471036171, 1.17232858907798, 1.44675812720393, 0.727078405331282,
1.36341361598635, 1.06120293299474, 1.06920290856811, 0.711007267992205,
1.39034247642439, 0.710873996527168, 1.30529753573398, 0.781191310196629,
0.921788181250106, 0.932214675722466, 0.752289683770589, 0.942392026874501
), year = c(3, 1, 4, 1, 2, 4, 1, 3, 4, 3, 4, 1, 2, 3, 4, 1, 1,
4, 1, 1, 1, 1, 4, 1, 3, 3, 1, 4, 1, 4, 2, 1, 1, 1, 3, 4, 3, 2,
2, 2, 3, 3, 1, 2, 3, 2, 3, 4, 4, 1), imd.decile = c(8, 2, 5,
5, 4, 3, 2, 8, 6, 4, 3, 6, 9, 2, 5, 3, 5, 6, 4, 2, 9, 11, 2,
8, 3, 5, 7, 8, 7, 4, 9, 7, 6, 4, 8, 10, 5, 6, 6, 11, 6, 4, 2,
4, 10, 8, 2, 8, 4, 3)), .Names = c("antibiotic", "year", "imd.decile"
), row.names = c(17510L, 6566L, 24396L, 2732L, 13684L, 28136L,
1113L, 15308L, 28909L, 21845L, 23440L, 1940L, 8475L, 22406L,
27617L, 4432L, 3411L, 27125L, 6891L, 6564L, 1950L, 5683L, 25240L,
5251L, 20058L, 18068L, 5117L, 29066L, 2807L, 24159L, 12309L,
6044L, 7629L, 2336L, 16583L, 23921L, 17465L, 14911L, 8879L, 13929L,
17409L, 19421L, 7239L, 11570L, 15283L, 8283L, 16246L, 27950L,
23723L, 4411L), class = "data.frame")
I am trying to graph imd.decile by antibiotic for each year
library(ggplot2)
p <- ggplot(df, aes(x = imd.decile, y = antibiotic, group = factor(year))) +
stat_summary(geom = "line", fun.y = mean)
p
How do I add the wave to colour the corresponding graph and add a legend (I can't seem to use the aes command correctly).

use R to remove header (6 lines) from .asc file (ESRI ascii grid) and export

I have over 800 .asc files (ESRI ascii grids) that each have a header consisting of 6 lines, then the raster data separated by spaces. Here is a small file as an example. I read it in using read.asciigrid (sp package).
new("SpatialGridDataFrame"
, data = structure(list(mydata.asc = c(4, 4, 4, 4, 3, 4, 4, 4, 1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4, 4, 4, 1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4,
4, 4, 1, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4, 4, 4, 6, 1, 1, 1, 1, 4, 4, 4,
4, 3, 4, 4, 4, 6, 1, 1, 1, 1, 4, 4, 4, 4, 3, 4, 4, 4, 6, 1, 1, 1, 1,
4, 4, 4, 4, 4, 4, 4, 4, 6, 6, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 6, 6,
1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 6, 6, 6, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 6)), .Names =
"mydata.asc", row.names = c(NA,
-143L), class = "data.frame")
, grid = new("GridTopology"
, cellcentre.offset = c(394984.42630274, 2671265.4912109)
, cellsize = c(25, 25)
, cells.dim = c(13L, 11L) )
, bbox = structure(c(394971.92630274, 2671252.9912109, 395296.92630274,
2671527.9912109), .Dim = c(2L, 2L), .Dimnames = list(NULL, c("min", "max")))
, proj4string = new("CRS"
, projargs = NA_character_ ) )
Here is what the file looks like if you view it with a text editor.
Here are the steps I would like to do
1) read in file
2) remove first 6 lines (header)
3) save file back out as .asc file with the same filename but in a different location
Of course, I'd like to do this to 800 files, but if I can figure out how to do this for one file, I should be able to write a function to loop through all files.
Thanks for any help.
-al
UPDATE:
This is the final code that worked for me, thanks to #Luca Braglia.
Set working directory
setwd("c:/temp/hdr/ascii")
newdir <- "c:/temp/hdr/ascii_no_hdr/"
files <- dir(pattern="*.asc")
for (my.file in files){
i <- read.table(my.file,skip=6,sep="")
write.table(i,file=paste(newdir,my.file,sep=""),sep="",row.names=FALSE,col.names=FALSE)
}
I didn't want the col and row names. A very simple and effective piece of code.
You can list all files, within a for loop read them all (using skip option of read.table)
## you are in the directory with your asc files
files <- dir(pattern="*.asc")
# loop
for (my.file in files) {
i <- read.table(my.file, skip = 6, sep = " ")
# change names here if you don't want V1, V2 ...
write.table(i, file = paste("new_dir", my.file, sep = "/"),
sep = " ", row.names = FALSE)
}

Resources