logo
down
shadow

Extract single plot from ggplot with facet_grid


Extract single plot from ggplot with facet_grid

Content Index :

Extract single plot from ggplot with facet_grid
Tag : r , By : besn
Date : November 28 2020, 11:01 PM

this one helps. I'm not sure why you wouldn't use subsetting, but you can extract individual facets from a facet grid.
library(ggplot2)
library(grid)
library(gtable)

p1 = ggplot(data = mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  facet_grid(. ~ am)


g1 = ggplotGrob(p1)


# Rows and columns can be dropped from the layout.

# To show the layout:
gtable_show_layout(g1)

# Which columns (and/or rows) to drop?
# In this case drop columns 5 and 6 to leave am = 0 plot
# Drop columns 4 and 5 to leave am = 1 plot

# am = 0 plot
g1_am0 = g1[,-c(5,6)]

grid.newpage()
grid.draw(g1_am0)


# am = 1 plot
g1_am1 = g1[,-c(4,5)]

grid.newpage()
grid.draw(g1_am1)

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

scatter plot of same variable across different conditions with ggplot facet_grid?


Tag : r , By : user157064
Date : March 29 2020, 07:55 AM
To fix the issue you can do I'd like to correlate the same column of a dataframe for points with distinct row values. For example, in the iris dataframe, I'd like to make three scatter plots comparing Petal.Length of virginica with that of versicolor, setosa with virginica and versicolor with setosa. I want it to appear just like a normal facet_grid or facet_wrap plot. For example, I can do: , It is better to group the data first. I'd do something like this:
# get Petal.Length for each species separately    
df1 <- subset(iris, Species == "virginica", select=c(Petal.Length, Species))
df2 <- subset(iris, Species == "versicolor", select=c(Petal.Length, Species))
df3 <- subset(iris, Species == "setosa", select=c(Petal.Length, Species))

# construct species 1 vs 2, 2  vs 3 and 3 vs 1 data
df <- data.frame(x=c(df1$Petal.Length, df2$Petal.Length, df3$Petal.Length), 
y = c(df2$Petal.Length, df3$Petal.Length, df1$Petal.Length), 
grp = rep(c("virginica.versicolor", "versicolor.setosa", "setosa.virginica"), each=50))
df$grp <- factor(df$grp)

# plot
require(ggplot2)
ggplot(data = df, aes(x = x, y = y)) + geom_point(aes(colour=grp)) + facet_wrap( ~ grp)

Plot several graphs using ggplot() and facet_grid()


Tag : r , By : kakashi_
Date : March 29 2020, 07:55 AM
around this issue I am wondering in how to plot several graphs in one screen using ggplot() and facet_grid() because I really need to repeat this process several times for different statistical variables. , I think this is what you want.
library(ggplot2)
library(reshape2)

# Fake some data
set.seed(1234)
nc <- 15
nr <- 20  
onms <- sprintf("Observation%d",1:nr)
pnms <- sprintf("Prediction%d",1:nr)
cnames <- sprintf("x%d",1:nc)

odf <- data.frame(Observations=onms)
pdf <- data.frame(Predictions=pnms)

for(i in 1:nc){
  vk1 <- 0.01*rnorm(nr)
  odf[[cnames[i]]] <- round(cumsum(vk1),3)
  vk2 <- 0.02*rnorm(nr)
  pdf[[cnames[i]]] <- round(cumsum(vk1) + cumsum(vk2),3)
}

# This is the data we need
head(odf)
head(pdf)

# Now change the pred. colnames so they don't collide with the obs. colnames
newpnames <- sprintf("p_x%d",1:nc)
names(pdf) <- c("series",newpnames)
names(odf)[1] <- "series"

# Merge the data into a long format
modf <- melt(odf,id.vars="series",measure.vars=cnames)
mpdf <- melt(pdf,id.vars="series",measure.vars=newpnames)   
mdf <- rbind(modf,mpdf)

# Now extract the fields we need into new columns
mdf$x <- as.numeric(gsub(".*[A-Za-z]","",mdf$variable))
mdf$frame <- as.numeric(gsub(".*[A-Za-z]","",mdf$series))
frameNames <- sprintf("Frame:%d",1:max(mdf$frame))
mdf$frame <- factor(sprintf("Frame:%d",mdf$frame),levels=frameNames)
mdf$kind <- substr(mdf$series,1,3)

# Finally plot it
ggplot(mdf) + geom_line(aes(x=x,y=value,color=kind)) + facet_wrap( ~ frame )

# ecdf version
ggplot(mdf,aes(x=value,color=kind)) + stat_ecdf(geom="step") + facet_wrap( ~ frame )
> head(odf)
  Observations     x1     x2     x3     x4     x5    x6     x7     x8     x9
1 Observation1 -0.012  0.014 -0.002 -0.002 -0.008 0.005  0.001 -0.010  0.001
2 Observation2 -0.009  0.004 -0.003 -0.010 -0.011 0.012  0.005 -0.005  0.002
3 Observation3  0.002 -0.005 -0.017  0.011 -0.015 0.014 -0.006 -0.012 -0.003
4 Observation4 -0.022 -0.008 -0.019  0.018 -0.017 0.021  0.001 -0.004 -0.019
5 Observation5 -0.018 -0.017 -0.010  0.037 -0.013 0.024  0.008 -0.012 -0.019
6 Observation6 -0.013 -0.027 -0.003  0.037 -0.007 0.031  0.011 -0.009 -0.026
    x10    x11    x12    x13   x14    x15
1 0.009 -0.012  0.005 -0.007 0.015 -0.007
2 0.028 -0.012  0.004  0.005 0.013 -0.018
3 0.028 -0.016  0.005 -0.012 0.026 -0.021
4 0.027 -0.025 -0.004 -0.008 0.026 -0.020
5 0.022 -0.021 -0.017 -0.006 0.019 -0.012
6 0.036 -0.019 -0.003  0.026 0.011  0.001
> head(pdf)
  Predictions     x1    x2     x3     x4     x5    x6     x7     x8    x9
1 Prediction1 -0.009 0.028  0.007 -0.009 -0.063 0.023  0.020 -0.022 0.000
2 Prediction2 -0.016 0.068 -0.005  0.011 -0.068 0.043  0.017 -0.036 0.007
3 Prediction3 -0.014 0.059 -0.017  0.045 -0.052 0.090  0.009 -0.047 0.021
4 Prediction4 -0.029 0.042 -0.029  0.050 -0.046 0.121 -0.019 -0.018 0.028
5 Prediction5 -0.038 0.032 -0.037  0.079 -0.024 0.130 -0.005 -0.026 0.031
6 Prediction6 -0.062 0.058 -0.027  0.087  0.022 0.124 -0.016 -0.036 0.047
     x10    x11    x12    x13    x14    x15
1 -0.027 -0.037  0.007  0.012  0.023 -0.026
2 -0.061 -0.029 -0.010  0.000  0.048 -0.027
3 -0.073 -0.035 -0.004 -0.003  0.048 -0.023
4 -0.045 -0.041  0.000 -0.001  0.048 -0.025
5 -0.034 -0.024 -0.038  0.037  0.030 -0.007
6  0.005 -0.020 -0.045  0.064 -0.002 -0.005

plot more than one column+facet_grid (ggplot)


Tag : r , By : Matthew Steed
Date : March 29 2020, 07:55 AM
this will help my data frame goes like this: , You've got a few issues to clean up here:
df <- melt(nut, id.vars=c('MEDIUM','NUMBER','DATE','DAY','TREAT')
pd=position_dodge(0.8)

ggplot(df, aes(x=MEDIUM, y=value, fill=variable)) +
  stat_summary(fun.y=mean, geom="bar", width=0.7, position=pd) + 
  stat_summary(fun.data=mean_cl_boot, geom="errorbar", position=pd, width=0.3) +
  facet_grid(. ~ TREAT) +
  theme_bw()
pd=position_dodge(0.4)

ggplot(df, aes(x=MEDIUM, y=value, colour=variable)) +
  stat_summary(fun.data=mean_cl_boot, geom="errorbar", position=pd, width=0.3) +
  stat_summary(fun.y=mean, geom="point", position=pd) + 
  facet_grid(. ~ TREAT) +
  theme_bw()

R plot using ggplot facet_grid add legend


Tag : r , By : lamberms
Date : March 29 2020, 07:55 AM
Does that help Using ggplot and faced_grid, I have a problem to visualize the entire name of type1 variable. The name is too long. How I can add a legend for avoid this problem? , Here is one option where we fill by type1.
ggplot(DF, aes(y=value, x=type1)) + 
  geom_boxplot(alpha=.3, aes(fill = type1)) + 
  ggtitle("TITLE") + facet_grid(type2 ~ number) +
  scale_x_discrete(name = NULL, breaks = NULL) + # these lines are optional
  theme(legend.position = "bottom")

How can I add a geometric shape or an annotation to a single ggplot graphic in `facet_grid`?


Tag : r , By : FuzzyHornet
Date : March 29 2020, 07:55 AM
it should still fix some issue I made a faceted graph using ggplot, and then tried to use the function annotate to create a grey highlighted area in one specific panel of the plot only.
  geom_rect(data=data.frame(Species='versicolor'), inherit.aes=FALSE,
            xmin = 6, xmax = 6.5, ymin= 0, ymax= Inf,
            fill = 'grey20', alpha = 0.2)
Related Posts Related QUESTIONS :
  • Is there an R function to retrieve values from a matrix of column names?
  • R;Too slow to overate loops for million vectors
  • How to optimize intersect of rows and columns in a matrix?
  • Format and export the output of Mann-Kendall test in R to excel from Rstudio
  • how to calculate cumsum with depreciation in a grouped dataframe?
  • reshape wide to long based on part of column name
  • How to get a hyperlink for the words in a description in an r dataframe?
  • shinymeta works locally but breaks when published to shinyapps.io
  • Deparse and (un)escape quotes
  • Regression table with clustered standard errors in R jupyter notebook?
  • Disaggregate quarterly data to daily data in R keeping values?
  • How to save output to console and file simultaneously in RStudio server?
  • Why does data.table j have a different environment when directly calling mget() vs calling mget() inside another functio
  • scale_fill_viridis_c color bar on a log scale
  • How to change the lab name corresponding to function in ggplot
  • R, filtering for an element in a list in a dataframe cell
  • Extracting only bottom temperature from 4d NetCDF file
  • How to add/wrap lines of text to .tex with .sh script
  • R - building new variables from sequenced data
  • Sum rows values one after the other
  • Nesting ifelse inside summarytools
  • How best to divide different levels of a factor by one another in dataframe in R?
  • Why does my code run multiple times before I type data into the table? How do I make an action button that creates a tab
  • How to impute missing values not at random?
  • Set the y limits of an added average line of a plotly plot
  • how to calculate a new column after grouping with dplyr
  • Extract data from rows creating new columns using R
  • Create a filled area line plot with plotly
  • When do I need parentheses around an if statement to control the sequence of a formula in R?
  • my graph in ggplot2 contains an "e" character in y-axis
  • Making variables immutable in R
  • R: Difference between the subsequent ranks of a item group by date
  • Match data within multiple time-frames with dplyr
  • Conditional manipulation and extension of rows in data.table also considering previous extensions without for-loop
  • Conditional formula referring to preview row in DF not working
  • Set hoverinfo text in plotly scatterplot
  • Histogram of Sums from Categorical/Binary Data
  • Efficiently find set differences and generate random sample
  • Find closest points from data set B to point in data set A, using lat long in R
  • dplyr join on column A OR column B
  • Replace all string if row starts with (within a column)
  • Is there a possibility to combine position_stack and nudge_x in a stacked bar chart in ggplot2?
  • How can I extract bounding boxes in a row-wise manner using R?
  • How do I easily sum up values in different columns?
  • Reading numeric Date value from CSV file to data.frame in "R"
  • R programming: creating a stacked bar graph, with variable colors for each stacked bar
  • How to identify all columns that contain binary representation
  • Filter different groups by different factor levels
  • Saving .xlsx file to disc, form http post request
  • Add an "all" option under the filter that selects the number of rows displayed in a datatable
  • How to select second column of every xts in list
  • Generate a frequency dataframe out of an input dataframe
  • Why manual autocorrelation does not match acf() results?
  • Merge 3 dataframes which are different to each other
  • remove adjacent duplicates from string
  • How to change the position of stacked stacked bar chart in ggplot in R?
  • How to divide each of a range a variables by a second range of variables in R
  • Why do I need to assemble vector before scaling in Spark?
  • How to select individuals which appear in multiple groups?
  • How can I fill columns based on values in another column?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com