Facet_grid with all panels with a free_y - ggplot2

I have a 6x6 grid (sites along the side and year along the top), showing abundance (y) over time(x).
I have used facet_grid to build the plot, using free_y. This has plotted a figure with each row having a shared y axis. I need to have a free_y for all the panels individually and I know that facet_grid doesnt allow this, while facet_wrap does. I would like to use facet_grid becuase it keeps the order of the panels, with columns for each year, and rows for each site.
I've tried using the lemon package with the facet_rep_grid function but this hasn't worked. Does anyone know how I can free_y across all the panels seperately?
Thanks

facet_wrap does this, and is what I use, although it does mean you have the faceting value as a title for each individual facet, which can be a pain.
ggplot(mpg, aes(displ, hwy, colour = as.factor(cyl))) +
geom_point() +
facet_wrap(year ~ drv,
scales = "free_y")

One suggestion is to use ggh4x::facet_grid2() to set independent y scales. (Disclaimer: I'm the author of ggh4x). Example with standard dataset below:
library(ggplot2)
ggplot(mpg, aes(displ, hwy, colour = as.factor(cyl))) +
geom_point() +
ggh4x::facet_grid2(vars(year), vars(drv),
scales = "free_y", independent = "y")
Created on 2022-03-11 by the reprex package (v0.3.0)

Another solution would be facet_rep_grid in the lemon package.
Sample code:
#install.packages("lemon")
library(lemon)
library(ggplot2)
ggplot(df)+
geom_line(aes(x=time, y=abundance, color=sites))+
lemon::facet_rep_grid(year~sites,
scales="free",
repeat.tick.labels = "all")+
theme(panel.background = element_blank(),
axis.line = element_line(size=0.5))+
labs(x="Time", y="Abundance", fill="Sites")+
theme_minimal()
Plot:

Related

ggplot geom_bar with errors not printing

Assigning means and se to a data frame and trying to construct geom_bar with error bars for 2 experimental treatments across two genders
library(ggplot2)
dff <- data.frame(group=c('NSI','NSI','SI','SI'),
gender = c('Female','Male','Female','Male'),
mean.Score =c(3.41,3.3,2.63,3.32),
se =c(1.92,2.03,1.73,2.21))
dff$group <- as.factor(dff$group)
dff$gender <- as.factor(dff$gender)
p <- ggplot(dff,aes(x= group,y=mean.Score,fill=gender))+
scale_fill_manual(values = c("#F34444", "#0066CC"))+
geom_bar(position = 'dodge',stat = 'identity',width=1.8)+
geom_errorbar(aes(ymin=mean.Score-se, ymax=mean.Score+se),
width=.2,
position=position_dodge(1.8))+
theme(plot.title = element_text(size = 10,hjust = 0.9))+
scale_x_discrete(limits=c('NSI','NSI','SI','SI'))+
ggtitle("Performance by Treatment & Gender")
plot(p)
Two treatments: NSI and SI. Across two genders: Female and Male; data is corresponding mean performance and standard error of that performance. Assigning to a data frame and trying to plot a histogram with error bars of the data. Code executes fine in the window, but then nothing shows up in the Plot window. Thanks for any help for a relative newbie!
Mary
probably go to tools > global options > pane layout, and make sure the plot is checked for the console window
example of where to check in rstudio

How to display centroids for categorical variables instead of arrows using function ggord?

I really can’t figure out how to display just the centroids for my categorical variables using the function ggord. If anybody could help me, that would be great.
Here is an example of what I’m trying to achieve using the dune data set:
library(vegan)
library (ggord)
library(ggplot2)
ord <- rda(dune~Moisture+ Management+A1,dune.env)
#first plot
plot(ord)
# second plot
ggord(ord)
#I tried to add the centroids, but somehow the whole plot seems to be differently scaled?
centroids<-ord$CCA$centroids
ggord(ord)+geom_point(aes(centroids[,1],centroids[,2]),pch=4,cex=5,col="black",data=as.data.frame(centroids))
In the first plot only the centroids (instead of arrows) for moisture and management are displayed. In the ggord plot every variable is displayed with an arrow.
And why do these plots look so different? The scales of the axes is totally different?
Something like this could work - you can use the var_sub argument to retain specific predictors (e.g., continuous), then just plot others on top of the ggord object.
library(vegan)
library(ggord)
library(ggplot2)
data(dune)
data(dune.env)
ord <- rda(dune~Moisture+ Management+A1,dune.env)
# get centroids for factors
centroids <- data.frame(ord$CCA$centroids)
centroids$labs <- row.names(centroids)
# retain only continuous predictors, then add factor centroids
ggord(ord, var_sub = 'A1') +
geom_text(data = centroids, aes(x = RDA1, y = RDA2, label = labs))

Highlight/multicolor substring of axis tick label in ggplot

I am curious about how to highlight or multicolor the text in axis of x, here is the example of output, how can I label the red color of 'TGFB1' within the word 'TGFB1-EGFR', this is the pair of ligand and receptor in biology. If you have some idea or know other package which do achieve this, please tell me, thanks in advance.
Best,
Wei
I find the ggtext github package very convenient in doing this. It allows html and markdown styling of text. Here is an example using the Iris dataset that you could apply on your own data.
Briefly, you wrap your labels in html colour coding and set the theme element to a markdown element.
library(ggtext) # remotes::install_github("wilkelab/ggtext")
library(ggplot2)
ggplot(iris, aes(Species, Sepal.Length)) +
geom_boxplot() +
scale_x_discrete(
labels = function(x) {
paste0("<i style='color:#FF0000'>Iris </i>",
"<i style='color:#0000FF'>", x ,"</i>")
}
) +
theme(axis.text.x = element_markdown())
Created on 2020-05-19 by the reprex package (v0.3.0)

barplot plot extra bars

I am fairly new to R, so I hope you can help me out with a simple solution. In a barplot in R, I want to add horizontal lines on top of the bars that represent the different categories on the x-axis (which represent expected values). The expected values vary per category. Here's a little piece of my script.
nem=c(0,1,2,3,4,5,6)
fish=c(103,72,44,13,3,1,1)
table=data.frame(nem,fish)
ticks=seq(1,6,1)
graph=barplot(fish,las=2,ylim=c(0,120),main="Number of nematodes per fish")
axis(1,at=graph,labels=c(0,1,2,3,4,5,6))
Hope you can help me out!
Image of barplot
I hope that can help you - just put the lines under your code.
linelength <- c(10,20,12,50,12,14,21)
xl <- seq(from=0.7, by=1.2, along.with = fish)
yl <- cbind(fish, fish + linelength)
for(z in 1:length(fish)){
lines(x=rep(xl[z], 2), y=yl[z,])
}

matplotlib pyplot side-by-side graphics

I'm trying to put two scatterplots side-by-side in the same figure. I'm also using prettyplotlib to make the graphs look a little nicer. Here is the code
fig, ax = ppl.subplots(ncols=2,nrows=1,figsize=(14,6))
for each in ['skimmer','dos','webapp','losstheft','espionage','crimeware','misuse','pos']:
ypos = df[df['pattern']==each]['ypos_m']
xpos = df[df['pattern']==each]['xpos_m']
ax[0] = ppl.scatter(ypos,xpos,label=each)
plt.title("Multi-dimensional Scaling: Manhattan")
for each in ['skimmer','dos','webapp','losstheft','espionage','crimeware','misuse','pos']:
ypos = df[df['pattern']==each]['ypos_e']
xpos = df[df['pattern']==each]['xpos_e']
ax[1] = ppl.scatter(ypos,xpos,label=each)
plt.title("Multi-dimensional Scaling: Euclidean")
plt.show()
I don't get any error when the code runs, but what I end up with is one row with two graphs. One graph is completely empty and not styled by prettyplotlib at all. The right side graphic seems to have both of my scatterplots in it.
I know that ppl.subplots is returning a matplotlib.figure.Figure and a numpy array consisting of two matplotlib.axes.AxesSubplot. But I also admit that I don't quite get how axes and subplotting works. Hopefully it's just a simple mistake somewhere.
I think ax[0] = ppl.scatter(ypos,xpos,label=each) should be ax[0].scatter(ypos,xpos,label=each) and ax[1] = ppl.scatter(ypos,xpos,label=each) should be ax[1].scatter(ypos,xpos,label=each), change those and see if your problem get solved.
I am quite sure that the issue is: you are calling ppl.scatter(...), which will try to draw on the current axis, which is the 1st axes of 2 axes you generated (and it is the left one)
Also you may find that in the end, the ax list contains two matplotlib.collections.PathCollections, bot two axis as you may expect.
Since the solution above removes the prettiness of prettyplot, we shall use an alternative solution, which is to change the current working axis, by adding:
plt.sca(ax[0_or_1])
Before ppl.scatter(), inside each loop.