ggarrange, combine multiple plots with ggplot
I have a list of plots (15 in total).
I want to arrange them in a single page with a 3x5 matrix
I used ggarrange with two plots
Now i want to do it with all the plots
Moran_plot_eu_std <-ggarrange(plots=plotlist,
common.legend = TRUE, legend = "bottom",
ncol = 3, nrow = 5)
But it doesn't work or send back error message
do you know?
how many words do you know
See also questions close to this topic
-
pivot_wider does not keep all the variables
I would like to keep the variable
cat
(category) in the output of my function. However, I am not able to keep it. The idea is to apply a similar function tom <- 1 - (1 - se * p2)^df$n
based on the category. But in order to perform that step, I need to keep the variable category.Here's the code:
#script3 suppressPackageStartupMessages({ library(mc2d) library(tidyverse) }) sim_one <- function() { df<-data.frame(id=c(1:30),cat=c(rep("a",12),rep("b",18)),month=c(1:6,1,6,4,1,5,2,3,2,5,4,6,3:6,4:6,1:5,5),n=rpois(30,5)) nr <- nrow(df) df$n[df$n == "0"] <- 3 se <- rbeta(nr, 96, 6) epi.a <- rpert(nr, min = 1.5, mode = 2, max = 3) p <- 0.2 p2 <- epi.a*p m <- 1 - (1 - se * p2)^df$n results <- data.frame(month = df$month, m, df$cat) results %>% arrange(month) %>% group_by(month) %>% mutate(n = row_number(), .groups = "drop") %>% pivot_wider( id_cols = n, names_from = month, names_glue = "m_{.name}", values_from =m ) } set.seed(99) iters <- 1000 sim_list <- replicate(iters, sim_one(), simplify = FALSE) sim_list[[1]] #> # A tibble: 7 x 7 #> n m_1 m_2 m_3 m_4 m_5 m_6 #> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #> 1 1 0.970 0.623 0.905 0.998 0.929 0.980 #> 2 2 0.912 0.892 0.736 0.830 0.890 0.862 #> 3 3 0.795 0.932 0.553 0.958 0.931 0.798 #> 4 4 0.950 0.892 0.732 0.649 0.777 0.743 #> 5 5 NA NA NA 0.657 0.980 0.945 #> 6 6 NA NA NA 0.976 0.836 NA #> 7 7 NA NA NA NA 0.740 NA
Created on 2022-05-07 by the reprex package (v2.0.1)
-
calculate weighted average over several columns with NA
I have a data frame like this one:
ID duration1 duration2 total_duration quantity1 quantity2 1 5 2 7 3 1 2 NA 4 4 3 4 3 5 NA 5 2 NA
I would like to do a weighted mean for each subject like this:
df$weighted_mean<- ((df$duration1*df$quantity1) + (df$duration2*df$quantity2) ) / (df$total_duration)
But as I have NA, this command does not work and it is not very nice....
The result would be this:
ID duration1 duration2 total_duration quantity1 quantity2 weighted_mean 1 5 2 7 3 1 2.43 2 NA 4 4 3 4 4 3 5 NA 5 2 NA 2
Thanks in advance for the help
-
I am to extract data from netCDF file using R for specific loaction the code i've written as showen and I have an error at the end of the code
I need some help with extracting date from NetCDF files using R , I downloaded them from cordex (The Coordinated Regional climate Downscaling Experiment). In total I have some files. This files have dimensions of (longitude, latitude, time) and the variable is maximum temperature (tasmax). At specific location, I need to extract data of tasmax at different time. In total I have some files. This files have dimensions of (longitude, latitude, time) and variable maximum temperature (tasmax). At specific location, I need to extract data of tasmax at different time.I wrote the code using R but at the end of code, an error appeared. Error ( location subscript out of bounds)
getwd() setwd("C:/Users/20120/climate change/rcp4.5/tasmax")
dir() library ("ncdf4") libra,-ry(ncdf4.helpers) library ("chron") ncin <- nc_open("tasmax_AFR-44_ICHEC-EC-EARTH_rcp45_r1i1p1_KNMI-RACMO22T_v1_mon_200601-201012.nc") lat <- ncvar_get(ncin, "lat") lon <- ncvar_get(ncin, "lon") tori <- ncvar_get(ncin, "time") title <- ncatt_get(ncin,0,"title") institution <- ncatt_get(ncin,0,"institution") datasource <- ncatt_get(ncin,0,"source") references <- ncatt_get(ncin,0,"references") history <- ncatt_get(ncin,0,"history") Conventions <- ncatt_get(ncin,0,"Conventions") tustr <- strsplit(tunits$value,"") ncin$dim$time$units ncin$dim$time$calendar tas_time <- nc.get.time.series(ncin, v = "tasmax", time.dim.name = "time") tas_time[c(1:3, length(tas_time) - 2:0)] tmp.array <- ncvar_get(ncin,"tasmax") dunits <- ncatt_get(ncin,"tasmax","units") tmp.array <- tmp.array-273.15 tunits <- ncatt_get(ncin,"time","units") nc_close(ncin) which.min(abs(lat-28.9)) which.min(abs(lon-30.2)) tmp.slice <- tmp.array[126,32981,] tmp.slice
Error in tmp.array[126, 32981, ] : subscript out of bounds
-
How to delete label above bar chart in R that's already in the legend?
this is my first post!
Just wondering how to remove these titles above the charts:
Here's the code for the diagram!
I imagine I'll have to use something like:
p + theme(axis.title.x = element_blank(), axis.title.y = element_blank())ggplot(data=bike_data_v4)+ geom_bar(mapping = aes(x=day_of_week,fill=member_casual))+ scale_x_discrete(limits = c("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"), labels = c("Sun","Mon","Tue","Wed","Thu","Fri","Sat"))+ #the discrete lines show how I rearranges the x-axis labels to go from sun-sat and be renamed to shorter text facet_wrap(~member_casual)+ labs(title="Weekly Rider Differences by Cyclist Type", subtitle="Members vs. Casual Riders", x = "Day of the Week", y = "Number of Overall Rides", caption="Data Provided by Google Capstone Project")+ scale_y_continuous(limits=c(0,500000), labels = scales::comma)+ #this combined scale_y_continuous(limits=c(0,500000) AND scale_y_continuous(labels=comma) theme_fivethirtyeight()+ labs(fill='Rider Type')+ theme(axis.title = element_text())
-
Scale_x_discrete breaks are not appearing
I'm creating a rank abundaunce curve for some species data. The y axis is the abundaunce (numeric) and the x axis is the factor "rank" of each species (one with the most abundance gets rank #1, and so forth)
This data is between rank 1-400, and so I want to set my own x axis limits ( i dont want to see every single label).
I confirmed that "ab" (which is abundaunce) is numeric and rank.freq (which is the rank) is a factor.
But, the x-axis scale just never shows up. What am I doing wrong?
rank.abun<- ggplot(HEMI ,aes(x =reorder(rank.freq, -ab), y = ab))+ geom_bar(stat = "identity")+ scale_x_discrete(breaks = c("700", "1000", "2000", "3000", "4000"), labels = c("700", "1000", "2000", "3000", "4000"))+ ## not sure why this isn't working labs(x = "Abundance Rank", y = "Abundance"); rank.abun
the data
X Species freq ab rank.freq 330 330 COUM 197 178.39 330 472 472 PEBR 139 149.50 472 548 548 KRGR 119 207.04 548 555 555 PECE 117 59.52 555 657 657 CAMI12 98 97.53 657 702 702 PEGR2 92 139.20 702
and the resulting plot
-
R: How to remove spikes/outliers on ggplot2
Given the following R script:
library(glue) library(ggplot2) library(tidyverse) library(magrittr) library(stringi) library(dplyr) ir.data <- read.csv(file="~/apps/mine/cajueiro_weather_station/sensor_data/temperature_data.csv", header = F) ir.data$V1 <- as.POSIXct(ir.data$V1, format = "%Y-%m-%dT%H:%M:%S", tz = "UTC") ir.data %>% pivot_longer(-V1, names_to = "Labels", values_to = "V") %>% ggplot(aes(x = V1, y = V, colour = Labels)) + labs( title = "IR-radiation-based sky temperature monitoring.", subtitle = glue::glue( "Samples from {ir.data$V1[1]}h to {tail(ir.data$V1, n=1)}h UTC-3." ), caption = "Cajueiro Weather Station - fschuindt.githhub.io/blog/weather" ) + geom_line(size = 1) + scale_color_manual( name = "Labels", values = c("#1e2975", "#ad1fa2"), # limits = c("V2", "V3"), labels = c("Ambient temperature.", "Sky temperature."), ) + xlab("Timestamp") + ylab("Measured temperature in °Celcius")
That produces the following plot:
From a dataset that looks like this:
2022-04-30T19:47:00,28.03,28.05 2022-04-30T19:47:02,27.99,28.01 2022-04-30T19:47:04,28.07,28.01 2022-04-30T19:47:06,28.05,28.05 2022-04-30T19:47:08,28.05,28.01 2022-04-30T19:47:10,28.03,28.01 2022-04-30T19:47:12,28.05,27.99 2022-04-30T19:47:14,28.07,28.01
How can I remove those temperature spikes that look more like verticals lines from the plot? I'm pretty sure those are sensors misreadings.
-
r - Plotting monthly time series data in R - cannot plot more than 10 series
I'm having a lot of trouble plotting my time series data in R Studio. My data is laid out as follows:
tsf
Time Series: Start = 1995 End = 2021 Frequency = 1 Jan Feb Mar Apr May Jun July Aug Sep Oct Nov Dec 1995 10817 8916 9697 10314 9775 7125 9007 6000 4155 3692 2236 996 1996 12773 12562 13479 14280 13839 9168 10959 6582 5162 4815 3768 1946 1997 14691 12982 13545 14131 14162 10415 11420 7870 6340 6869 6777 6637 1998 17192 15480 14703 16903 15921 13381 13779 9127 6676 6511 5419 3447 1999 13578 19470 23411 18190 18979 17296 16588 12561 10405 8537 7304 4003 2000 20100 29419 30125 27147 27832 23874 19728 15847 11477 9301 6933 3486 2001 16528 22258 22146 19027 19436 15688 14558 10609 6799 6563 4816 2480 2002 14724 19424 21391 17215 18775 13017 14385 10044 7649 6598 4497 2766 2003 17051 20182 18564 18484 15365 12180 13313 8859 6830 6371 3781 2012 2004 16875 20084 21150 19057 16153 13619 14144 9599 7390 5830 3763 2033 2005 20002 24153 23160 20864 18331 14950 14149 11086 7475 6290 3779 2134 2006 24605 26384 24858 20634 18951 15048 14905 10749 7259 5479 3074 1509 2007 29281 26495 25974 21427 20232 15465 15738 10006 6674 5301 2857 1304 2008 32961 24290 20190 17587 12172 7369 16175 6822 4364 2699 1174 667 2009 10996 8793 7345 5558 4840 4833 4355 2422 2272 1596 948 474 2010 10469 11707 12379 9599 8893 8314 7018 5310 4683 3742 2146 647 2011 13624 13470 12390 11171 9359 9240 6953 3653 2861 2216 1398 597 2012 14507 10993 10581 9388 7986 5481 6164 3736 2783 2442 1421 774 2013 10735 9671 10596 8113 7095 3293 9306 4504 3257 2832 1307 639 2014 15975 11906 11485 11757 7767 3390 14037 6201 4376 3082 1465 920 2015 20105 15384 17054 13166 9027 3924 21290 8572 5924 3943 1874 847 2016 27106 21173 20096 14847 10125 4143 22462 9781 5842 3831 1846 679 2017 26668 16905 17180 13427 9581 3585 21316 8105 4828 3255 1594 601 2018 25813 16501 16088 11557 9362 3716 20743 7681 4397 2874 1647 778 2019 22279 14178 14404 13794 9126 3858 18741 7202 4104 3214 1676 729 2020 20665 13263 10239 1338 1490 2189 15329 7360 5747 4189 1468 1032 2021 16948 11672 10672 8214 7337 4980 20232 8563 6354 3882 2167 832
When I attempt rudimentary code to plot the data I get the following
plot(tsf) 'Error in plotts(x = x, y = y, plot.type = plot.type, xy.labels = xy.labels, : cannot plot more than 10 series as "multiple"'
My data is monthly and therefore 12 months exceed this apparent limit of 10 graphs.I've been able to make some plot by excluding two months but this is not practical for me. I've looked at lots of answers on this, many of which recommending
ggplot() {ggplot2}
The link below had data most closely resembling my data but I still wasn't able to apply it.
issues plotting multivariate time series in R
Any help greatly appreciated.
-
How to plot a Sequential Bayes Factor as participants are added
I am currently analyzing eye-tracking data using the Sequential Bayes Factor method, and I would like to plot how the resulting Bayes Factor (BF; calculated from average looking times) changes as participants are added.
I would like the x-axis to represent the number of participants included in the calculation, and the y-axis to represent the resulting Bayes Factor.
For example, when participants 1-10 are included, BF = [y-value], and that is one plot point on the graph. When participants 1-11 are included, BF = [y-value], and that is the second plot point on the graph.
Is there a way to do this in R?
For example, I have this data set:
ID avg_PTL <chr> <dbl> 1 D07 -0.0609 2 D08 0.0427 3 D12 0.112 4 D15 -0.106 5 D16 0.199 6 D19 0.0677 7 D20 0.0459 8 d21 -0.158 9 D23 0.0650 10 D25 0.0579 11 D27 0.0463 12 D29 0.00822 13 D30 0.00613 14 D36 -0.0484 15 D37 0.0312 16 D39 0.000547 17 D44 0.0336 18 D46 0.0514 19 D48 0.236 20 D51 -0.000487 21 D60 0.0410 22 D61 0.0622 23 D62 0.0337 24 D64 -0.125 25 D65 0.215 26 D66 0.200
And I calculate the BF with:
bf.mono.correct = ttestBF(x = avg_PTL_mono_correct$avg_PTL)
Any tips are much appreciated!
-
Julia plot hline! doesn't work with multiple threads
I have a simple simulation and I want to plot errors on 3 distinct figures. To speed things up I wanted to introduce a little bit of parallel computing.
Threads.@threads for i in 1:3 plt = plot(t, err[:, i], linecolor=:blue, label=[""], linewidth=3) hline!(plt, [0], linestyle=:dash, linecolor=:black, label=[""]) xlabel!(L"t") ylabel!(L"e_%$i") savefig(plt, "fig/Staubli_Slotine_Li$i.pdf") end
Everything stops working when I try running julia with
-t3
flagERROR: LoadError: TaskFailedException Stacktrace: [1] wait @ ./task.jl:334 [inlined] [2] threading_run(func::Function) @ Base.Threads ./threadingconstructs.jl:38 [3] top-level scope @ ./threadingconstructs.jl:97 nested task error: KeyError: key :annotations not found Stacktrace: [1] pop!(h::Dict{Symbol, Any}, key::Symbol) @ Base ./dict.jl:587 [2] pop_kw!(dd::RecipesPipeline.DefaultsDict, k::Symbol) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/utils.jl:57 [3] _update_subplot_args(plt::Plots.Plot{Plots.PGFPlotsXBackend}, sp::Plots.Subplot{Plots.PGFPlotsXBackend}, plotattributes_in::Dict{Symbol, Any}, subplot_index::Int64, remove_pair::Bool) @ Plots ~/.julia/packages/Plots/nzdhU/src/args.jl:2058 [4] _subplot_setup(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:277 [5] plot_setup!(plt::Plots.Plot{Plots.PGFPlotsXBackend}, plotattributes::Dict{Symbol, Any}, kw_list::Vector{Dict{Symbol, Any}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/pipeline.jl:138 [6] recipe_pipeline!(plt::Any, plotattributes::Any, args::Any) @ RecipesPipeline ~/.julia/packages/RecipesPipeline/F2mWY/src/RecipesPipeline.jl:87 [7] _plot!(plt::Plots.Plot, plotattributes::Any, args::Any) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:208 [8] plot!(::Plots.Plot; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:198 [9] plot!(; kw::Base.Pairs{Symbol, V, Tuple{Vararg{Symbol, N}}, NamedTuple{names, T}} where {V, N, names, T<:Tuple{Vararg{Any, N}}}) @ Plots ~/.julia/packages/Plots/nzdhU/src/plot.jl:188 [10] #xlabel!#484 @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [11] xlabel! @ ~/.julia/packages/Plots/nzdhU/src/shorthands.jl:416 [inlined] [12] macro expansion @ ~/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:29 [inlined] [13] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})(onethread::Bool) @ Main ./threadingconstructs.jl:85 [14] (::var"#88#threadsfor_fun#1"{UnitRange{Int64}})() @ Main ./threadingconstructs.jl:52 in expression starting at /home/jcebulsk/Documents/studia/master_thesis/master_thesis_code/sym_scripts/Staubli_Slotine_Li.jl:26
If I comment out
hline!
the script runs without any issue.It looks like I can't have both
hline
and parallel operation.