Tag: ggplot

r – ggplot multiple legends into one box

I am trying to combine multiple partial legends (i.e. for two different features of one plot) legends into one box. My real-life data is a plot made with geom_sf() with fill colors for polygons and a specific border highlighted made with geom_sf()with a line. Since the line is only one…

Continue Reading r – ggplot multiple legends into one box

ggplot2 – How to wrap graphs by categories while keeping the same width of bars with ggplot in R?

I am struggling with using facet_grid() and facet wrap() with ggplot(). I would like to be able to wrap the different stacked barcharts for every two categories (of the variable Department here) but at the same time have the same width of bars. The first action can be achieved with…

Continue Reading ggplot2 – How to wrap graphs by categories while keeping the same width of bars with ggplot in R?

r – ggplot two histograms in one plot

You can reference some of the other calculated values from stat functions using a notation that you may have seen before: ..value… I’m not sure the proper name for these or where you can find a list documented, but sometimes these are called “special variables” or “calculated aesthetics”. In this…

Continue Reading r – ggplot two histograms in one plot

ggplot2 – Create graphs by group using ggplot in R

I’m relatively new to using ggplot2 in R and have been struggling with this for awhile. I have figured out how to get everything from one data frame on a graph (that is pretty easy…), and how to write a loop function to get each observation (id in the example…

Continue Reading ggplot2 – Create graphs by group using ggplot in R

Fixing abrupt changes/transitions in animated ggplot

I was wanting to make an animated ggplot of daily values for countries over the course of a year. I was able to do that thanks to some helpful questions/answers here. While the code below successfully makes a gif, the changes/transitions when countries move up or down/overtake one another is…

Continue Reading Fixing abrupt changes/transitions in animated ggplot

Plotting date intervals in ggplot2

I have a dataset which has a bunch of date intervals (i.e. POSIXct format start dates and end dates). In the example provided, let’s say it’s each period is associated to when someone was in school or out of school. I’m interested in plotting the data in ggplot2, each row…

Continue Reading Plotting date intervals in ggplot2

Writing ggplot custom geometry function

stat_accum <- function(mapping = NULL, data = NULL, geom = “point”, position = “stack”, …, show.legend = NA, inherit.aes = TRUE) { layer( data = data, mapping = mapping, stat = StatAccum, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( na.rm = na.rm,…

Continue Reading Writing ggplot custom geometry function

r – ggplot add horizontal line to grouped categorical data and share legend

I think for readability, it’s better to separate them out. However, for formatting purpose, you sure can bring them as close as you want by dropping the legend.title (not just assigning it an empty string) and adjusting the legend.margin and legned.spacing. For instance, library(tidyverse) data(mtcars) y = mean(mtcars$mpg) x =…

Continue Reading r – ggplot add horizontal line to grouped categorical data and share legend

Tutorial on Box Plot in ggplot2 with Examples – MLK

Introduction Boxplots are a useful visualization technique to understand the distribution and outliers in a dataset. In this article, we will go through the tutorial for box plot in ggplot2 function of R which is a popular visualization package. We will first understand the syntax of ggplot2 function geom_boxplot() for…

Continue Reading Tutorial on Box Plot in ggplot2 with Examples – MLK

Error on final object when generating ggplot objects in for loop with dplyr select()

I want to make many plots using multiple pairs of variables in a dataframe, all with the same x. I store the plots in a named list. For simplicity, below is an example with only 1 variable in each plot. Key to this function is a select() call that is…

Continue Reading Error on final object when generating ggplot objects in for loop with dplyr select()

ggplot2 – R knitr Markdown: Output Plots within For Loop

I am using child Rmd files in markdown, also works in sweave. in Rmd use following snippet: “`{r run-numeric-md, include=FALSE} out = NULL for (i in c(1:num_vars)) { out = c(out, knit_child(‘da-numeric.Rmd’)) } “` da-numeric.Rmd looks like: Variabele `r num_var_names[i]` ———————————— Missing : `r sum(is.na(data[[num_var_names[i]]]))` Minimum value : `r min(na.omit(data[[num_var_names[i]]]))`…

Continue Reading ggplot2 – R knitr Markdown: Output Plots within For Loop

Using logic in listcols (ggplot2 edition)

I am trying to produce a slightly different result from a purrr::map iteration depending on a condition. Say I have this code producing plots and storing them in a dataframe: library(tidyverse) #> — Attaching packages ————————————— tidyverse 1.3.1 — #> v ggplot2 3.3.5 v purrr 0.3.4 #> v tibble 3.1.6…

Continue Reading Using logic in listcols (ggplot2 edition)

Decimal digits in `Slope Graph` with `ggplot2`

Following a former question I opened few weeks ago: Slope Chart – ggplot2 I face another issue, concerning the numeric values reported in the graph. Even specifying the decimal digits I need (exactly 3) with any of the two commands: y=round(y, digit = 3) at the endof the code or…

Continue Reading Decimal digits in `Slope Graph` with `ggplot2`

Draw a fill (bar?) beneath line-segments using ggplot

I’m hoping there is an easy geom_ that is not geom_polygon to do what I’m trying to do here. I’d like to have “fills” extend down to 0 on the y-axis and split up by the grouping similar to how the line segments are split up by the “device_period” in…

Continue Reading Draw a fill (bar?) beneath line-segments using ggplot

How to draw several lines with ggplot? ( R, Ggplot2 )

Problem : ( Scroll to solution ) This code draws 2 lines dd = list(data.frame(rates=1:5), data.frame(rates=2:6), data.frame(rates=3:7)) library(ggplot2) library(zoo) g = ggplot(, aes(1:5)) g <- g + geom_line(aes(y = dd[[1]]$rate[index(dd[[1]]) <= 5]), colour=”#000000″) g <- g + geom_line(aes(y = dd[[2]]$rate[index(dd[[2]]) <= 5]), colour=”#000000″) g But this code draws 1 line…

Continue Reading How to draw several lines with ggplot? ( R, Ggplot2 )

how to add colored tick label to ggplot2?

One option to add some colored squares beneath your colored labels would be via an additional geom_text layer. As the label I use a filled square with UTF-8 code “u25A0”. Using some fake random data to mimic your real data: library(ggplot2) ggplot(df, aes(x = Var2, y = Var1)) + geom_tile(fill…

Continue Reading how to add colored tick label to ggplot2?

Ggplot: heatmap based on two vectors ( R, Ggplot2 )

Problem : ( Scroll to solution ) I am trying to plot data as a heat map in ggplot2. I understand that you’d normally have to have x, y, and z coordinated to plot x against y and then color by z. I have found plenty of heat map examples…

Continue Reading Ggplot: heatmap based on two vectors ( R, Ggplot2 )

ggplot2 – How to change the color of each facet in a scatter plot in R?

I’m trying to visualize two bivariate quantitative variables, disaggregated by the categorical variable stu_tech_cat. I would like each facet to have a different color, but have been unsuccessful in achieving that so far. Below is my code: tech_stu <- ggplot(mydata, aes(y = EEScore, x= subtct, fill = stu_tech_cat, color)) +…

Continue Reading ggplot2 – How to change the color of each facet in a scatter plot in R?

Why does stacked barplot ggplot in R sum values?

When I make the following, I want just to compare the three years not to sum them. And the actual code sums them even if I don’t tell it to do it. Any clue? hoteles <- tibble::tribble( ~Hotel , ~Año, ~Ingresos , “Hawaiian Club” , “1993”, 450000 , “Hawaiian Club”…

Continue Reading Why does stacked barplot ggplot in R sum values?

h2o.explain function – RDocumentation

Description The H2O Explainability Interface is a convenient wrapper to a number of explainabilty methods and visualizations in H2O. The function can be applied to a single model or group of models and returns a list of explanations, which are individual units of explanation such as a partial dependence plot…

Continue Reading h2o.explain function – RDocumentation

R ggpmisc::ggplot — EndMemo

R ggplot — ggpmisc ggplot() initializes a ggplot object. It can be used to declare the input spectral object for a graphic and to optionally specify the set of plot aesthetics intended to be common throughout all subsequent layers unless specifically overridden. ggpmisc::ggplot is located in package ggpmisc. Please install…

Continue Reading R ggpmisc::ggplot — EndMemo

r – Scatter plot with ggplot2

I am trying to make scatter plot with ggplot2. Below you can see data and my code. data=data.frame( gross_i.2019=seq(1,101), Prediction=seq(21,121)) ggplot(data=data, aes(x=gross_i.2019, y=Prediction, group=1)) + geom_point() This code produce chart below So now I want to have values on scatter plot with different two different colors, first for gross_i.2019 and…

Continue Reading r – Scatter plot with ggplot2

Change size of label annotations in a ggplot

I am trying to change text label sizes inside my plot (not the axes, rather the label annotations) I am working with a phyloseq object but I don’t think that matters. Here is the code and the output. Any suggestions? plot_ordination(prokaryote_ra, ordBC, color = “Stage”, label=”SampleID”) + ggtitle(“PCoA: Bray-Curtis”) graph…

Continue Reading Change size of label annotations in a ggplot

Why is the plot generated from ggplot not showing up?

The line plt = ggplot(…. is not right, for a few reasons. plt is the name you’ve given the pylab module. plt = will delete it! data=df is a keyword argument (because of the data= part). They have to go after positional arguments. See the keyword entry of the Python…

Continue Reading Why is the plot generated from ggplot not showing up?

Data Visualization using Plotnine and ggplot2 in Python

  Data Visualization is the technique of presenting data in the form of graphs, charts, or plots. Visualizing data makes it easier for the data analysts to analyze the trends or patterns that may be present in the data as it summarizes the huge amount of data in a simple…

Continue Reading Data Visualization using Plotnine and ggplot2 in Python

r – ggplot plotting bars that show the sum of other columns

Hello and happy holidays my data looks like: ID <- c(1,2,3,4) time_1 <- c(12,20,31,18) time_2 <- c(5,8,11,7) time_3 <- c(15,5,9,17) total_time <- c(32,33,51,42) data_test<- data.frame(ID,time_1,time_2,time_3,total_time) data_test %>% glimpse() $ ID <dbl> 1, 2, 3, 4 $ time_1 <dbl> 12, 20, 31, 18 $ time_2 <dbl> 5, 8, 11, 7 $…

Continue Reading r – ggplot plotting bars that show the sum of other columns

ggplot2 and cumsum() – Stackify

Here’s a test data which uses plyr‘s transform to calculate the cumulative sum first and then apply that data to plot using ggplot2: set.seed(45) DF <- data.frame(grp = factor(rep(1:5, each=10)), x=rep(1:10, 5)) DF <- transform(DF, y=runif(nrow(DF))) # use plyr to calculate cumsum per group of x require(plyr) DF.t <- ddply(DF,…

Continue Reading ggplot2 and cumsum() – Stackify

ggplot function error – General

So I have been trying to visualize my data using ggplot. I used the following command: ggplot(data = inv_database, mapping= aes(x = Gender,y = Total.Monthly.Income))+ geom.point(size=5)+ geom.line(colour=”red”) The response I am getting; Error in ggplot(data = inv_database, mapping = aes(x = Gender, y = Total.Monthly.Income)) : could not find function…

Continue Reading ggplot function error – General

r – How to plot a bar plot by ggplot2 and sort bars in non-alphabetical order

This question already has answers here: Closed 11 hours ago. I’m trying to plot a boxplot by ggplot2 and it sorts the boxes in alphabetical order, but I want to change their order. How can I do that? Thanks for any help. Here is my code:…

Continue Reading r – How to plot a bar plot by ggplot2 and sort bars in non-alphabetical order

[R] question about for loop

y, c, and f only exist in the context of mac2 If you want to use them, you’ll have to write mac2$y, mac2$c, or mac2$f (or the [[ versions mac2[[“y”]], mac2[[“c”]], or mac2[[“f”]]) Combining that with index i would then look like mac2$y[[i]] or mac2[[i, “y”]] Also, I think you…

Continue Reading [R] question about for loop

legend troubles in ggplot scatter plot

ggplot(df, aes(x=x, y=y)) + geom_point(shape=ifelse(nrow(df)>49, 1, 16)) + geom_smooth(method=lm, fill=”white”, aes(colour=”Fitted”, linetype=”Fitted”)) + geom_smooth(method=lm, fill=”red”) + geom_abline(intercept=0, slope=1, colour = “blue”, linetype = “solid” ) + geom_line(data = data.frame(x=0, y=0), aes(colour = “Ideal”, linetype = “Ideal”)) + scale_colour_manual(name=”Lines”, values=c(“Ideal”=”blue”, “Fitted”=”red”)) + scale_linetype_manual(name=”Lines”, values=c(“Ideal”=”solid”, “Fitted”=”twodash”)) + opts(title=”Method Comparison”) + labs(x=”Control”, y=”Evaluation”)…

Continue Reading legend troubles in ggplot scatter plot

Custom ggplot2 axis and label formatting

You can set the prefix in dollar_format for euros instead of dollars: scale_y_continuous(labels=dollar_format(prefix=”€”)) + That takes care of the scientific notation issue. To get everything in thousands, you could just divide by 1000 when you create the summary. To reduce clutter, you could leave out the euro symbol in the…

Continue Reading Custom ggplot2 axis and label formatting

r – Avoiding eval-parse or do.call

I am trying to select a theme from ggplot2 based on some string given. For demo purposes, consider the following code: library(dplyr); library(ggplot2) mtcars %>% ggplot(aes(mpg, wt))+ geom_point() -> p all_ggplot2_funs <- getNamespaceExports(“ggplot2”) p + eval(parse(text=paste0(all_ggplot2_funs[grep(“theme_”, all_ggplot2_funs)][15], “()”))) This works fine and would allow me to use theme_minimal. However, from…

Continue Reading r – Avoiding eval-parse or do.call

ggplot2 – R ggplot – ploting multiple variables with sub-categories in the same plot with two axes

I have this data: date area people_tested positive_cases positive 2021-12-09 Total 76282.0 402.0000 0.005300000 2021-12-10 Total 84023.0 389.0000 0.004600000 2021-12-09 Total_3da NA 382.3333 0.004900000 2021-12-10 Total_3da NA 377.6667 0.004933333 2021-12-09 Paris_3da 75257.4 NA NA 2021-12-10 Paris_3da 71553.6 NA NA and I would like to create a plot with a line…

Continue Reading ggplot2 – R ggplot – ploting multiple variables with sub-categories in the same plot with two axes

ggplot: remove lines at ribbon edges

You can remove the border using the colour argument: ggplot(d, aes(Time, y, color = Object, fill = Object)) + geom_line(size = 2) + geom_ribbon(aes(ymin = lower, ymax = upper), alpha = .3, colour = NA) geom_ribbon understands linetype aesthetic. If you want to map linetype to a variable include it…

Continue Reading ggplot: remove lines at ribbon edges

r – ggplot2 Set geom_point Size according to a Factor

I am trying to set the size of geom_point according to a factor. I know it is not advised, but my data is extremely unbalanced (the minimum value is 6 while the maximum is larger than 10,000). I am trying to make the size of the points reflect the total…

Continue Reading r – ggplot2 Set geom_point Size according to a Factor

r – Filling up histograms with ggplot – Changing colours

Try: df4 <- data.frame(rnorm(10000,100,10)) colnames(df4) <- c(“Value”) histi_base2 <- ggplot(df4, aes(x=Value)) histi5 <- histi_base2 + geom_histogram(binwidth = 1, alpha=0.8, fill=”red”, color=”black”) + labs(title=”Your second Histogram”, subtitle = “now in solid red”) histi5 With fill you’re changing the color inside the bars and with color you’re changing the borders. PS: sorry,…

Continue Reading r – Filling up histograms with ggplot – Changing colours

Draw Cumulative Histogram in R (Example)

  In this R tutorial you’ll learn how to draw the cumulative sum of a vector in a histogram. Table of contents: Here’s how to do it!   Example Data The following data is used as basement for this R programming language tutorial: set.seed(258967) # Create example data data <-…

Continue Reading Draw Cumulative Histogram in R (Example)

[Solved] In ggplot add different text annotations on facet charts

library(tidyverse) ggplot(data = mtcars, aes(x = disp, y = mpg)) + geom_point() + scale_x_continuous(breaks = seq(10,500, 10), limits = c(0,500))+ geom_vline(xintercept = 70, color=”red”)+ annotate(geom = ‘text’, x = 10, y = 20, size = 4, fontface=”bold”, lineheight = .95, label = “One”, color=”whitesmoke”)+ facet_wrap(. ~ gear, ncol = 1)+…

Continue Reading [Solved] In ggplot add different text annotations on facet charts

r – Geom_text not legible with greater values using ggplot2

While creating a ggplot2 graph using geom_text, the text is legible as long as the y values are somehow within the same range. (y limits = 121) However, when I add a new variable with a greater range, the text is illegible (y limits = 271) This is the code…

Continue Reading r – Geom_text not legible with greater values using ggplot2

What does L mean? – General

Hello everyone! I am new to R and am trying to understand some codes that other people have written. The code I am focusing on right now was written by @andresrcs in this thread: df %>% pivot_longer(c(“PA”, “PUA”), names_to = “type”) %>% ggplot(aes(y = Country, x = value, fill =…

Continue Reading What does L mean? – General

r – How to avoid too much space around polar chart in ggplot

This is my dataframe: my_df <-structure(list(Statistic = c(“Shots on target %”, “Shots on target %”, “% of dribblers tackled”, “% of dribblers tackled”, “Ground passes”, “Ground passes”, “Passes Completed”, “Passes Completed”, “Live-ball passes”, “Live-ball passes”, “Passes Attempted (Right)”, “Passes Attempted (Right)”, “Passes Attempted”, “Passes Attempted”, “Successful Pressure %”, “Successful Pressure…

Continue Reading r – How to avoid too much space around polar chart in ggplot

r – Changing the background width in ggplot

I want to be able to change the background width, shown below, to fit both the legends and the title; how is it possible? Image containing the pie charts The legends are changeable because of the app so I need the background color to fit the legends with the title…

Continue Reading r – Changing the background width in ggplot

scale_x_discrete not showing data some data and hiding another

I want to plot a graph showing data by fiscal year. The problem I have is that ggplot is showing a point that does not exist in the data frame containing the information, and not painting another that really exists. Could you please masters of ggplot help me? Thank you…

Continue Reading scale_x_discrete not showing data some data and hiding another

shade alternate days with POSIXct timestamp data

I can plot a line of a variable vs timestamp (plot p1 below). However, I’d like to shade the plot for alternate days. The data has an entry once an hour for two days. dat <-structure(list(TIMESTAMP = structure(c(2L, 3L, 14L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 4L, 5L, 6L,…

Continue Reading shade alternate days with POSIXct timestamp data

xlim not working for discrete values [ggplot2]

I’m trying to set xlim and ylim in ggplot put using the below: ylim=c(0, 1.5) + xlim=c(0,100) + OR coord_cartesian(xlim = c(0, 100), ylim = (0,1.5)) + Seems to throw this error: Error in scale_x_discrete(breaks = c(0, 50, 100), labels = c(0, : non-numeric argument to binary operator Is this…

Continue Reading xlim not working for discrete values [ggplot2]

[Solved] R Alignment of images in tables with markdown, rstudio and knitr

I’m trying to create a standard monthly report for work in PDF format using Rstudio and I want to incorporate ggplot output with a table of figures – a new chart, one per cell on each row. I’m new to markdown, latex, pandoc and knitr so this is a bit…

Continue Reading [Solved] R Alignment of images in tables with markdown, rstudio and knitr

FAQ: Intro to Visualization with R – The ggplot() function – Uncategorized

This community-built FAQ covers the “The ggplot() function” exercise from the lesson “Intro to Visualization with R”. Paths and CoursesThis exercise can be found in the following Codecademy content: Analyze Data with R Learn RLearn ggplot2 FAQs on the exercise The ggplot() function There are currently no frequently asked questions…

Continue Reading FAQ: Intro to Visualization with R – The ggplot() function – Uncategorized

Merge and Perfectly Align Histogram and Boxplot using ggplot2

since yesterday I am reading answers and websites in order to combine and align in one plot an histogram and a boxplot generated using ggplot2 package. This question differs from others because the boxplot chart needs to be reduced in height and aligned to the left outer margin of the…

Continue Reading Merge and Perfectly Align Histogram and Boxplot using ggplot2

For loop in ggplot for multiple time series viz ( R, Time Series )

Problem : ( Scroll to solution ) I need to make multiple individual plots of each time series (column) in my dataset: github.com/rhozon/datasets/raw/master/multiple_time_series_dataset.csv I thought of some for loop that loops through each column and plots each graph individually. ggplot(df, aes(x = timestamp, y = for loop for each column)…

Continue Reading For loop in ggplot for multiple time series viz ( R, Time Series )

r – ggplot2 vertical colorbar title right centered

Here is a solution, inspired in this SO post.Note that in the question you have fill = guide_colourbar(.) when it should be colour = guide_colourbar(.). library(ggplot2) ggplot(df, aes(x=img_type, y=metric),show.legend = FALSE) + geom_point(aes(size = abs_corr, colour=corr))+ scale_size(range =c(-0.1,20) )+ scale_colour_gradient2( low = “#7e1952”, high = “#2f7a9a”, space = “Lab”, na.value…

Continue Reading r – ggplot2 vertical colorbar title right centered

date – Create Stacked “Progress” Bar Chart in R with ggplot

I am looking for a way to use ggplot to create a variation of a stacked bar chart. More of like a “progress bar” chart. I have Dates on the x axis, and a categorical variable “activity” on the y axis. Each activity has a “Red”, “Yellow”, or “Green” status….

Continue Reading date – Create Stacked “Progress” Bar Chart in R with ggplot

Annotate Rotated Text Label to ggplot2 Graph in R (Example Code)

This page demonstrates how to add a rotated text label to a ggplot2 graphic in R programming. Preparing the Example data(iris) # Example data head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3…

Continue Reading Annotate Rotated Text Label to ggplot2 Graph in R (Example Code)

r – Where can I find documentation on the `..*..` ggplot options?

Here are all of the ..*.. options mentioned in the ggplot2 help files (or at least those help files that can be brought up by typing ?”<func>”, where “<func>” refers to one of the functions exported by ggplot2). library(ggplot2) ## Read all of the ggplot2 help files and convert them…

Continue Reading r – Where can I find documentation on the `..*..` ggplot options?

sf – R studio busy when library() a package

I’m trying to import packages by using library(). The packages I want to use are ‘sf’, ‘rnaturalearth’, ‘rnaturalearthdata’. I have successfully installed those packages. But when I run the library(), the rstudio is just keep loading, the chunk is always in running mode (with a red stop symbol). I can…

Continue Reading sf – R studio busy when library() a package

r – Adding significance levels manually to grouped ggplot

I have made a grouped ggplot using facet_wrap and added bars showing the level of significance using the “ggsignif” package. However, I would like to specify the level of significan myself. I know it is possible if you do it for an individual plot, but can it be done when…

Continue Reading r – Adding significance levels manually to grouped ggplot

Break on x and y axis on a ggplot – General

Hi, I get some data from an experiment that I would like to plot with ggplot2.The problem I have is that both measures have a huge difference. To make it more appreciable, I would like to set axis break on x and y axis for the same plot.I found the…

Continue Reading Break on x and y axis on a ggplot – General

r – Two plots within one facet in ggplot2

I have two types of data to create two types of plot, bar and line. They have different y axis, but same x axis. They are each categorized by the same category levels Example Code: data <- data.frame( Station = sample(LETTERS[seq( from = 1, to = 4 )],50, rep =…

Continue Reading r – Two plots within one facet in ggplot2

Expression in ggplot2 facet labels

I would like to have an R expression in a ggplot2 facet label. Let’s say I’m plotting the tips data.frame: library(reshape2) > head(tips) total_bill tip sex smoker day time size 1 16.99 1.01 Female No Sun Dinner 2 2 10.34 1.66 Male No Sun Dinner 3 3 21.01 3.50 Male…

Continue Reading Expression in ggplot2 facet labels

r – ggplot: Try to plot boxplots with geom_rect on its background, but keep having error with object “variable” not found

I was almost desperate with this error after working on this for 4 hrs, googled and looked from past posts already. Here is my data structure: str(tcga_exp) ‘data.frame’: 11775 obs. of 5 variables: $ cohort: chr “BRCA-Basal.Tumor” “BRCA-LumA.Tumor” “BRCA-LumB.Tumor” “BRCA-LumA.Tumor” … $ exp : num 6.35 5.54 6.56 5.05 5.98…

Continue Reading r – ggplot: Try to plot boxplots with geom_rect on its background, but keep having error with object “variable” not found

Are these samples good enough for DEA analysis?

Are these samples good enough for DEA analysis? 0 Hi all, Are these samples good enough for DEA analysis? Because I think the tumor and normal samples are not well separated. Here is my code: NormalizedCounts.scaled <- t(scale(t(NormalizedCounts) , scale = F)) pc <- prcomp(NormalizedCounts.scaled) pcr <- data.frame(pc$rotation[,1:3] , Group…

Continue Reading Are these samples good enough for DEA analysis?

making y-axis labels bold in ggplot (x-axis is set bold but y-axis label doesn’t change)

making y-axis labels bold in ggplot (x-axis is set bold but y-axis label doesn’t change) I am trying to set axis labels and ticks bold in ggplot but y-axis labels is not setting to bold. Please suggest what I should add to the script. Below is a reproducible example. I…

Continue Reading making y-axis labels bold in ggplot (x-axis is set bold but y-axis label doesn’t change)

r – Position Trend line regression equation in ggplot

i am trying to plot trend lines equation with R square for three variable (SA,SA1,SA2) using ggplot geom_smooth(). While plotting three variables i get overlapping equation. I tried to adjust the y lab position using stat_regline_equation(label.y = c(1.78e15,3.9e17,2.5e15)) but miserably failed in doing so. DATA LINK (Requirement: 3 trend lines…

Continue Reading r – Position Trend line regression equation in ggplot

Adjust the legends distance to the x-axis?

ggplot2: Adjust the legends distance to the x-axis? I want to shrink the legends distance to the x-axis, but I can’t find a way to do it. Is it possible? Example code: library(ggplot2) ggplot(mtcars, aes(x = gear, y = mpg, fill = gear)) + geom_bar(stat = “identity”) + theme(legend.position =…

Continue Reading Adjust the legends distance to the x-axis?

r – ggplot bar graph with flipped direction of bars

Here is a tidyverse solution Libraries library(tidyverse) Data df <- tibble( y = letters[1:15], p = runif(15,5,100), g = as.factor(rep(0:1,c(5,10))) ) Code df %>% #Create auxiliary variable, where for a determined group the percentage become negative mutate( p2 = if_else(g == 0, -p,p), y = fct_reorder(y,p2) ) %>% ggplot(aes(p2,y, fill…

Continue Reading r – ggplot bar graph with flipped direction of bars

Transparency and Alpha levels for ggplot2 stat_density2d with maps and layers in R

Transparency and Alpha levels for ggplot2 stat_density2d with maps and layers in R Can anyone offer suggestions as to the best way to deal with transparency and alpha levels with many layers (with reference to ggplot2)? In the sample code below, it becomes very difficult to see individual state borderlines…

Continue Reading Transparency and Alpha levels for ggplot2 stat_density2d with maps and layers in R

README

README ggmatplot is a quick and easy way of plotting the columns of two matrices or data frames against each other using ggplot2. Overview ggplot2 requires wide format data to be wrangled into long format for plotting, which can be quite cumbersome when creating simple plots. Therefore, the motivation for…

Continue Reading README

ggplot, drawing multiple lines across facets

ggplot, drawing multiple lines across facets I drew two panels in a column using ggplot2 facet, and would like to add two vertical lines across the panels at x = 4 and 8. The following is the code: library(ggplot2) library(gtable) library(grid) dat <- data.frame(x=rep(1:10,2),y=1:20+rnorm(20),z=c(rep(“A”,10),rep(“B”,10))) P <- ggplot(dat,aes(x,y)) + geom_point() +…

Continue Reading ggplot, drawing multiple lines across facets

AYUSH_MALAKAR_HW6.doc – Course IST 687 Assignment HW 6 Name Ayush Malakar Date library’ggplot2#including package#Step-1 AQ_dataset

################################################ Course: IST 687# Assignment: HW 6# Name: Ayush Malakar# Date: 08/17/2021# ###############################################library(‘ggplot2’) #including package#Step-1AQ_dataset<- airquality #loading the dataset into a new variable#Step-2AQ<- na.omit(AQ_dataset) #removing NA’s from the dataset#Step-3 (1)#1x <- ggplot(AQ, aes(x=Ozone)) #defining plot and aestheticsx<- x+geom_histogram(bins =5, colour=’black’, fill=’white’) # defining the shape and structure of the histogramx…

Continue Reading AYUSH_MALAKAR_HW6.doc – Course IST 687 Assignment HW 6 Name Ayush Malakar Date library’ggplot2#including package#Step-1 AQ_dataset

Labeling Clusters in ggplot

Labeling Clusters in ggplot 1 I have a data matrix I extracted from seurat and I want to plot the tSNE plot by using ggplot. I don’t know how to label the clusters on the plot with 0..15. Help is appreciated. ggplot single cell • 1.3k views This is what…

Continue Reading Labeling Clusters in ggplot

How do I access inflection points in Seurat object?

How do I access inflection points in Seurat object? 0 I ran the following code below to calculate inflection points for the UMI counts for my single cell data using Seurat. seurat_obj <- CalculateBarcodeInflections(seurat_obj,barcode.column = “nCount_RNA”,group.column = “orig.ident”,threshold.low = NULL,threshold.high = NULL) I want to obtain the inflection points so…

Continue Reading How do I access inflection points in Seurat object?

Boxplot (ggplot2) not working as expected

I’m trying to plot a simple boxplot where I get 15 boxplots for respondents age of 15 “Cadernos” (15 surveys, surveys A, B, C .. to O). But that’s not working as expected. I have already tried to switch places to the “Cadernos” (surveys) and “Idade” (age) variables. Any idea?…

Continue Reading Boxplot (ggplot2) not working as expected

Data visualization with R and ggplot2

ggplot2 package in R Programming Language also termed as Grammar of Graphics is a free, open-source, and easy-to-use visualization package widely used in R. It is the most powerful visualization package written by Hadley Wickham. It includes several layers on which it is governed. The layers are as follows: Building…

Continue Reading Data visualization with R and ggplot2

GGplot x-limits help? : RStudio

Dataframe containing dates and amount of short-time workers in Germany. Want to make a simple bar graph, however, it still shows December and October even if I specifically exclude these, I’ve been trying to find a solution for a while and I can’t figure it out (PNG shows Plot and…

Continue Reading GGplot x-limits help? : RStudio

r – Creating a graph to show values for different groups

Here is a small example how you could apply tidyr::pivot_longer and ggplot to create the desired graph. library(ggplot2) data <- data.frame(age= c(“16-24”, “25-34”, “35-44”, “45-54”), “y2014” = c(100,200,300,400), “y2015” = c(250,350,450,550), “y2016” = c(240, 340,440,550)) dataLong <- tidyr::pivot_longer(data, cols=c(“y2014”, “y2015”, “y2016”)) dataLong$year <- as.numeric(sub(“.”, “”, dataLong$name)) ggplot(dataLong) + geom_point(aes(x=year, y=value,…

Continue Reading r – Creating a graph to show values for different groups

R how to correct for multiple comparisons in ggplot correlations?

I have the following dataset: structure(list(Age_group = structure(c(4L, 2L, 2L, 2L, 4L, 2L, 2L, 4L, 3L, 1L, 2L, 1L, 1L, 4L, 1L, 2L, 1L, 4L, 3L, 4L, 4L, 1L, 2L, 2L, 1L, 2L, 1L, 3L, 3L, 2L, 2L, 3L, 4L, 3L, 2L, 4L, 2L, 2L, 3L, 4L, 4L, 4L, 1L,…

Continue Reading R how to correct for multiple comparisons in ggplot correlations?

ggplot2 each group consists of only one observation-plotting two lines on one graph

Beginner R user here. I am trying to graph two simple lines using the following data frame: date_of_case <- c(“7/12/2020”, “7/13/2020”, “7/14/2020”, “7/15/2020”, “7/16/2020”, “7/17/2020”, “7/18/2020”, “7/19/2020”, “7/20/2020”, “7/21/2020”, “7/22/2020”, “7/23/2020”, “7/24/2020”, “7/25/2020”, “7/26/2020”, “7/27/2020”, “7/28/2020”, “7/29/2020”, “7/30/2020”, “7/31/2020”, “8/01/2020”, “8/02/2020”, “8/03/2020”) Masked <- c(25, 23, 20, 20.5, 20, 20,…

Continue Reading ggplot2 each group consists of only one observation-plotting two lines on one graph

r – ggplot: multiple time periods on same plot by month

I am trying to plot multiple time-periods on the same time-series graph by month. This is my data: pastebin.com/458t2YLg. I was trying to avoid dput() example but I think it would have caused confusion to reduce the sample and still keep the structure of the original data. Here is basically…

Continue Reading r – ggplot: multiple time periods on same plot by month

About outliers and non -separated samples in PCA

About outliers and non -separated samples in PCA 0 Hi all, I have plotted PCA for my samples(Tumor and Normal) in some cancer types. I have used the HTSeq-counts data from TCGA. Then I’ve normalized them by DESeq2 and the total normalized counts are in cnt dataframe. Head of cnt:…

Continue Reading About outliers and non -separated samples in PCA

r – How to add multiple arrows to a path according to line direction using ggplot2?

I have a data frame that I want to plot a path from. The data frame also indicates the direction the arrows should have. I have been using the ggplot2 package and the geom_path() function for this, however, I want to add arrows that indicate the direction of the path….

Continue Reading r – How to add multiple arrows to a path according to line direction using ggplot2?

SeuratTheme function – RDocumentation

Usage SeuratTheme()CenterTitle(…)DarkTheme(…)FontSize( x.text = NULL, y.text = NULL, x.title = NULL, y.title = NULL, main = NULL, … )NoAxes(…, keep.text = FALSE, keep.ticks = FALSE)NoLegend(…)NoGrid(…)SeuratAxes(…)SpatialTheme(…)RestoreLegend(…, position = “right”)RotatedAxis(…)BoldTitle(…)WhiteBackground(…) Examples # NOT RUN { # Generate a plot with a dark theme library(ggplot2) df <- data.frame(x = rnorm(n = 100, mean…

Continue Reading SeuratTheme function – RDocumentation

r – different color scales for same aesthetic in different layers in ggplot2, without unstable packages

is it possible to have multiple color scales for different layers? I emulated what I would like to archive by using a fill aesthetic for a geom_point with shape=21 in the example below. library(tidyverse) test <- tibble( x=c(1:4, 1:4), y=c(1:4, 2:5), a=factor(c(“a”, “a”, “b”, “b”, “a”, “a”, “b”, “b”)), A=factor(c(“A”,…

Continue Reading r – different color scales for same aesthetic in different layers in ggplot2, without unstable packages

Create violin plot with specific value label that corresponding to graph

Example data. # Counts df <- as.data.frame(sapply(seq(2, 10, 2), function(x) rnorm(10, x, 1))) colnames(df) <- paste0(“group_”, 1:5) df$val <- paste0(“val_”, 1:10) > df group_1 group_2 group_3 group_4 group_5 val 1 0.4267759 4.599173 6.256323 8.534080 12.778423 val_1 2 2.9344611 3.649858 7.141283 9.299478 10.735906 val_2 3 0.8156248 3.363994 7.285855 7.503840 9.755979 val_3…

Continue Reading Create violin plot with specific value label that corresponding to graph

Bioinformatics Scientist in Gaithersburg, MD

We are currently searching for a Bioinformatics Scientist to provide support to the National Institutes of Health (NIH). This opportunity is a full-time position with MSC, and it is on-site in Gaithersburg, MD. Duties & Responsibilities Work independently and collaboratively to develop or optimize procedures that improve the throughput of…

Continue Reading Bioinformatics Scientist in Gaithersburg, MD

how to make box plot of specific row with group of sample in R

I am a new baby in R, I would like to ask for help to make the boxplot with the group I have 2 files, file 1 is the value of the samples (gene expression) test.txt gene group1.1 group1.2 group2.1 group2.2 a1 12 13 12 12 a2 2 3 25…

Continue Reading how to make box plot of specific row with group of sample in R

How to output MDS plot for RNAseq samples with ggplot2?

Dear all. I am trying to output an MDS plot to understand the relationship between RNAseq data. I was able to output the MDS plot using “diffExpr.P0.001_C2.matrix” output by edgeR. However, I would like to use ggplot2 to output it in a more readable form. I have tried the following…

Continue Reading How to output MDS plot for RNAseq samples with ggplot2?

help with mosaic plots

I’m trying to plot a mosaic style plot using geom_tile of the common GO terms from a DE experiment. As expected each GO term has multiple DE proteins associated with it. I thought I’d plot the GO ID on the x axis and fill each tile with a protein id….

Continue Reading help with mosaic plots

Finding the significance of the overlap between 2 or more gene sets using simulation in R.

TLDR: Example R function to calculate significance of overlap of 2 or more gene sets. genes_all is a vector that contains all genes, and gene_sets takes a list of vectors for each gene set. I encourage people to read the full tutorial and attempt to reproduce the code themselves (especially…

Continue Reading Finding the significance of the overlap between 2 or more gene sets using simulation in R.

karyoploteR: uncircle your genomes

Hi all, I’d like to present karyoploteR, an R/Bioconductor package we have developed to plot any data on any genome in non-circular layouts. The goal of this project was to develop a tool as flexible as Circos, but easier to use and representing genomes as straight lines instead of circles,…

Continue Reading karyoploteR: uncircle your genomes

Doubts with Stacked barplot using R ggplot2

Doubts with Stacked barplot using R ggplot2 0 Hello! I am trying to plot some data using R but I am having some problems doing it. I have a data frame with two columns (genes and and type of mutation) and looks like: genes variant MLH1 Intronic ATR 5′ UTR…

Continue Reading Doubts with Stacked barplot using R ggplot2

How to change the default font in ggplot 2

How to change the default font in ggplot 2 0 Hi! I want to change the font of my scatterplot created with ggplot2 and use Arial as font. I did first check the default font so I did: windowsFonts() And I get: $serif [1] “TT Times New Roman” $sans [1]…

Continue Reading How to change the default font in ggplot 2

problem in y axis in barplot+ggplot

problem in y axis in barplot+ggplot 1 Hi every body I want to plot barplot using ggplot. my data is: X1 X2 2367 تولید کل 23 هندوانه 11 خیار 97 گوجه 0 سیب 107 پیاز 2 کلزا 0 سویا 2 آفتابگردان 748 چغندرقند 0 پنبه 22 نخود 6 عدس 29…

Continue Reading problem in y axis in barplot+ggplot

Rshiny – ggplot – density plot

Hi, I’m trying to do a density plot in Rshiny. I find it confusing with this error Error: StatBin requires a continuous x variable: the x variable is discrete.Perhaps you want stat=”count”? My data looks like: t_data_gene ENSG S45 545 S43 4588 S36 454 S33 4685 … I used: ggplot(t_data_gene,…

Continue Reading Rshiny – ggplot – density plot

Violion plot with statistics

Violion plot with statistics 0 Hi I am using Seurat for scRNA-Seq analysis. Along the analysis, i used Seurat’s VlnPlot function as the following: VlnPlot(Myeloid.object, features=”Mki67″, split.by = ‘Sample’, pt.size = 0) The feature is then represented in a different color for each Sample, and is divided by cluster. I…

Continue Reading Violion plot with statistics

lfcShrink probelm in many 0 count genes RNA-seq data

Hi, Dr love. I post a question about weird MAplot or volcano plot of DESeq2 diff result and also in biostar. ATpoint give a useful answer about too many 0 count genes and prefiltering. It seems that too many 0 count genes makes lfc shrink have a probelm. And I…

Continue Reading lfcShrink probelm in many 0 count genes RNA-seq data

weird MAplot or volcano plot of DESeq2 diff result

Hi, every one. I find a werid MAplot or volcano plot of DESeq reuslt. I am wondering whether you can give me some advice. This diff result is from two cell type bulk RNA-seq. I use two specific marker to get these two cell type using Flow cytometer. I alreadly…

Continue Reading weird MAplot or volcano plot of DESeq2 diff result

R Programming – how to make a simple heat map

R Programming – how to make a simple heat map 5 Hi can anyone guide me how to make a simple heat map in R? Heatmap R • 264 views There is github.com/XiaoLuo-boy/ggheatmap which is fully ggplot in case you feel more comfortable with it rather than the suggested pheatmap/ComplexHeatmap…

Continue Reading R Programming – how to make a simple heat map

R Programming

R Programming 4 Hi can anyone guide me how to make a simple heat map in R? in Heatmap R • 201 views There is github.com/XiaoLuo-boy/ggheatmap which is fully ggplot in case you feel more comfortable with it rather than the suggested pheatmap/ComplexHeatmap packages and want to have a consistent…

Continue Reading R Programming

Highly used R packages with no Python equivalent

The biggies are obviously DESeq2, limma and edgeR, but they are massive packages doing some very complex statistics, and also have dependency trees that would need to be considered. Depending on your background, you might want to look into the rtracklayer/GenomicRanges eco-system. While I personally am not a fan, I…

Continue Reading Highly used R packages with no Python equivalent