Questions
Browse questions with relevant R Language tags
5,412 questions
Has recommended answermove inset plot legend
One option would be to add a legend to your main plot for which I use a fake invisible geom_point and remove the legend for your inset plot. As I don't have your dataset dat.eez.usa1 I simply used the ...
How to adjust x axis in coefficient plot with sjPlot's plot_model when x value range is smaller than -1,1?
As plot_model uses coord_flip under the hood you have to set the limits= for the "x" axis using scale_y_continuous: library(sjPlot) #> Learn more about sjPlot with 'browseVignettes("...
Ploting weekly data with base::plot with unique and evenly spaced labels
We can use seq.Date and axis.Date: plot(exampledata$Date, exampledata$Cases, main="Weeks by Cases", ylab="Cases", ylim=c(500000,900000), xlab="", ...
Divide one column to three add fill up missing numbers
This is probably better done using regex, but here is a tidyverse way: library(tidyr); library(dplyr) df |> # take the first character for Matches1 separate_wider_position( Matches, c(...
How to put a ggplot into a Word doc using Officer in R?
While the flextable package provides a convenience function to replace a bookmark with a flextable object, the officer only provides functions to replace a bookmark with text or an image. But one ...
Adding p-value and r-value in separate lines in correlogram using ggpairs in R
One option to achieve your desired result would be to use a customized function for which I adapted the source code of ggally_cor: library(GGally) my_ggally_cor <- function(data, ...
Make axis lines start from specific values in ggplot
You can achieve your desired result using the cap= argument of guide_axis (introduced with ggplot2 3.5.0) which allows to cap the axis at the first break (aka "lower") or the last break (aka ...
ggplot: How to merge two legend boxes and give legend keys any desired order?
You can achieve your desired result easily by working with one dataset which includes all categories and by converting variable to a factor. Then use a filtered dataset for each of the geoms, map ...
scale_fill_gradient2 colors do not reach the upper limit, even though the data does [duplicate]
If you want a dark green color for the upper limit then perhaps you want scale_fill_gradientn? Even when setting the limits with scale_fill_gradient2 the colors are evenly spaced or positioned along ...
How to use lapply on strings so that they end up grouped together?
You don't really need an lapply here. You can create the vector and then write it out all in one go with write(vctrs::vec_interleave(letters, numbers), file="Text_attempt.txt") Other ...
multiple times addition of two columns with dplyr
I would do it with two across in this case, although pivoting might be a better option for more complex operations. library(dplyr) a |> mutate(across(matches(".x$"), .names = "{...
R devtools::install(): how to install to user-local library?
If you check out the ?devtools::install help page, you'll see a note in the "Details" section that says To install a package in a non-default library, use withr::with_libpaths(). You can ...
R index, filter then match on multiple criteria. Easy in excel, not so in r
Here are two possible options to achieve your desired result without the need to store the untreated value for each weed type in a separate variable: library(dplyr, warn.conflicts = FALSE) df |> ...
Legend fails to show a category in ggplot when this category only has partial values
Personally I would simply use facetting: set.seed(123) library(ggplot2) ggplot(mydata, aes(x = n1, y = values, colour = model)) + geom_line(size = 0.6) + facet_wrap(~n, labeller = labeller(n ...
ggplot2: Add carriage return to facet grid label without generating extra columns
The issue is that you missed to add scales="free" to facet_wrap in your second code. Also note that facet_grid also allows to use a labeller=: library(ggplot2) consonant_df$p_m <- factor(...
How to create a variable based on unique counts within a time interval by multiple time points and grouping variable?
A dplyr solution: right_join( x.df, y.df |> mutate(end = index_date + time_from_index, start = `year<-`(end, year(end) - 1)), join_by(idnr, between(date_of_dispensing, start, end)) ) |> ...
How do I combine text names within an ordered transcription of dialogue?
Using data.table, split on ": ", group by relid, then paste it back per group: df[, c("name", "text") := tstrsplit(x, ": ", fixed = TRUE) ][, .(text = paste(...
Pass element form character vector in loop to function and use in assign
I'd suggest to return a dataframe from the function. Then use lapply to call that function, the outputs from the lapply will be then assigned to a list object that would hold all the dataframes. ...
How to change legend key shape for ggtree [closed]
If you have an up-to-date version of ggplot, you can use the key_glyph parameter to change the glyph. Using some example data from ggtree (sorry, I'm not going to download all that): library(ggtree) ...
Adding outliers to a boxplot from precomputed summary statistics
Note that layers inherit aesthetics by default. If an aesthetic is not shared, don't specify it in the main ggplot() call. Also, avoid using "$" in aes() calls. Use data= with different data ...
R get local variable from formula
By default get will look for Y in the the current environment of the call to get, which is just what is available in foo itself (i.e. pos = -1). One of the nice things about R formulas is that they ...
R How to reframe data to connect start and stop times
Since each has multiple sessions, we can create an indicator that increments each time a new "start" event happens. Try df %>% arrange(time_s) %>% group_by(whaleID, behaviour, ...
Mutate/cut to bin grouped data by grouped break points
One option would be to use split to split your dataset (and the boundaries) by groups, then bin each split individually: library(dplyr, warn = FALSE) library(purrr) iris2 <- iris |> ...
What does "training" the data mean in the internals of ggplot2?
In ggplot2 terms, 'training' means keeping track of possible values. For continuous variables, this means keeping track of the range and for discrete variables, that means keeping track of the levels. ...
geom_histogram cluster values with same fill category together
Ordering is by factor levels. Using forcats we can e.g. do: ggplot( data, aes(onset_date, fill = category, group = fct_reorder(factor(grouping), category)) ) + geom_histogram( breaks = ...
Find index of two identical values in succession for the first time
As clarified by OP, if the data is always increasing and starts duplicating on the last value, we just need to check unique length: lengths(lapply(list(a, b, c), unique)) # [1] 7 4 2
ggplot access inherited data object in scale_y_continuous [duplicate]
This doesn't directly answer your question, but to access the data, I'd make a plotdata dataframe then call that dataframe for setting limits: plotdata <- diamonds %>% filter(cut %in% c("...
Customization of plots created with the ale package
The labels for the horizontal lines are added via a secondary axis. Hence, one option would to get rid of these labels would be to overwrite the y scale. As you want to apply your modifications to all ...
Complete and fill missing rows with groups of uneven length
We can use statar::fill_gap(): library(dplyr) df %>% group_by(district) %>% statar::fill_gap(year, full = TRUE) %>% tidyr::fill(executive.name:party, .direction = "down") %...
How to get a true scatterplot matrix from GGally?
I don't see an (easy) option to achieve your desired result using ggpairs. But one option would be to build your pairsplot from scratch using ggmatrix which allows for more fine-control over the ...
What is the problem with my R code for solving and plotting a coupled system of ODE's?
Here is a model based on the SIRD model described on wikipedia, with your mu adjustment: sird_equations <- function(time, variables, parameters) { with(as.list(c(variables, parameters)), { dS ...
How to find if an ID appears in each group? [closed]
You can do this: library(dplyr) filter(dat, n_distinct(month) == 12, .by = recordID)
Exporting summary.betareg and summary.gam from list to csv
The issue is that broom does not provide a tidy method for objects of class summary.gam whereas for linear models aka models of class lm we have both a tidy.lm and a tidy.summary.lm method. While the ...
eulerr venn diagram missing small intersection
Using ellipse works fine for your data, we can use residuals error plots to check, it shows which overlaps are under/over-represented, 0 meaning exact: library(gridExtra) fit1 <- euler(sizes) fit2 ...
Cell value breakdown and string split with uneven length
Using stringr, dplyr, and tidyr: df2 |> separate_wider_delim(party, delim = fixed('-'), names_sep = '', too_few = 'align_start') |> mutate(across( starts_with('party'), \(s) ...
How to manually calculate survival probabilities using flexsurvspline models [closed]
The problem is that the parameters in the model are used to build splines from which the predictions are made. Trying to do this yourself from scratch would be very complex, and would be reinventing ...
How to set the same width of the multiple plots in R ggplot2?
One easy option to achieve your desired result with less code would be to use facetting which however requires to reshape your data. Additionally to apply the limits individually per panel I use ggh4x:...
How do I pass aesthetics to stat_summary in ggplot2?
When using stat_summary you have to use after_stat to map the computed mean value on the label aes, where in case of stat_summary the computed value is stored in a column named y. Note: I switched to ...
How to group by one column and then a second column to summarize
Here's a similar approach as the one of Edward's: read.table(text = "ID.1 ID.2 Name 5 6 Apple1 5 7 Applee 6 7 Applye ...
use of meta::forest() for plotting data
By the sounds of things, your data is in this format: data #> study_ID risk ratio lb.conf.int ub.conf.int #> 1 A 2.70 1.71 4.31 #> 2 B 2.33 1....
Trying to create a grouped barchart in R - producing a stacked one instead
As the variable mapped on fill is a numeric aka continuous variable you have to convert to a discrete or categorical variable using e.g. factor or explicitly map on the group aes: library(ggplot2) ...
Display all levels in legend of ggplotly object
We can add a dummy row (schoolname == NA) with "Excellent" rating, then that level is shown in the legend without getting plotted. Moreover, you had a typo where your levels in cut() did not ...
Convert a list into a tibble with nested columns
Perhaps something like: list_transpose(lst, default = NA, template = unique(unlist(map(lst, names)))) |> as_tibble() |> mutate(across(where(is.list), \(l) if (all(lengths(l) == 1)) unlist(...
Pad column numbers while using separate_wider_delim in R
You can specify the names, e.g. like so: df %>% separate_wider_delim( fruits_selected, delim = "+", names = sprintf("%02d", 1:3), names_sep = '_' ) If ...
How to add semicircles overlying geom_point in ggplot2
A more elaborated option would be to use some custom shapes. The approach below builds on this answer by @AllanCameron (which I already applied here) and this answer by @Baptiste to create the custom ...
ggsurvplot Interprets Number of Observations as Levels in newdata Argument
I don't have a complete answer. I think you need to provide 1 row for newdata per group, which works for the plot, but not for the table. sfit <- survfit( cox_model_single_111758446, newdata = ...
Apply command for complex functions and calculations on a dataset in R
Using the tidyverse I would write it something like: cals <- function(column, df){ var <- df |> group_by(.data[[column]]) |> summarise(ans = sum(val_1) ^ 2 + sum(val_2) ^ 2) |>...
Sorting calendar plot with geom_segment() + fix scale
To fix the order make sure that the your start date column actually contains the start date for each event. To this end I added two new columns. Afterwards arrange by the start date before setting yy. ...
Is there a way to add a pop-up window to facet_wrap ggplot titles that shows title descriptions in Quarto?
One option would be to use ggiraph which allows to make a ggplot2 interactive. For your use case it's sufficient to leverage facet_wrap_interactive and labeller_interactive to add a tooltip to the ...
How to draw the outermost line using scatter plot and geom density line?
We could use ggalt::geom_encircle(): library(ggplot2) library(ggalt) set.seed(1) df <- data.frame(x = rnorm(200), y = rnorm(200)) ggplot(df, aes(x = x, y = y)) + geom_point() + ...
Simply submit a proposal, get it approved, and publish it.
See how the process works