Ggvegan autoplot plot boundaries - r

I have done CCA- and RDA analysis in R with vegan and used autoplot.cca to generate plots. However, the plot boundaries are not constant and adjust autmatically (to what I do not know). Some plots return a horizontally very narrow plot
I have tried some suggestions like adding:
autoplot() +
labs(x=NULL, y=NULL) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0))
But this doesn't resolve anything. The code for plotting is below. I'm not making any fancy calls on formatting earlier in the code.
print(autoplot(my.cca, geom = "text", title = paste(i, "_sites_params_Wetter"), layers = c("sites", "biplot")) +
#geom_point(aes(my.cca)) +
#geom_hline(yintercept = 0) +
#geom_vline(xintercept = 0) +
theme(legend.position = "none")
)
Example output shared in link (don't have enough rep to post images):
I essentially plot in a loop, and the plots vary in area. I would like to be able to control the dimensions of the plotting area, and also make sure all labels are 100% within the area.
How do I do this?
Here is some example code to play with
x<-c("vegan", "ggplot2", "ggvegan")
lapply(x, require, character.only = TRUE)
data(package = "vegan")
data(mite)
data(mite.env)
my.cca <- cca(mite ~ ., data=mite.env)
autoplot(my.cca, geom = "text", layers = c("species", "biplot")) +
theme(legend.position = "none")

Related

How can I adjust the linetype in an already existing ggplot model in R?

To examine an interaction effect in my research I've created post hoc slopes using the function “emtrends” of the package emmeans (version 1.4.5.; Lenth, 2020) and visualized it in a plot using 'emmip'. I've used the code below:
emtrends(model_c, pairwise ~ Condition, var = "prsa_clean$meat_amount_c")
emmip(model_c, Condition ~ meat_amount_c, cov.reduce = range, ylab = "Favourability", xlab = "Meat consumption")
The resulting plot shows the 3 slope lines of my 3 conditions in blue/green/red lines, but doesn't adhere to the APA standards for figures, so I'm trying to adjust it using ggplot2. I manage to successfully edit the background and linesizes to my liking using the code below:
plot <- emmip(model_c, Condition ~ meat_amount_c, cov.reduce = range, ylab = "Favourability", xlab = "Meat consumption")
plot <-plot +theme_bw() + geom_line(size = 1.25)
However, I would like the lines to be different types. I've found the appropriate code to adjust this with ggplot is to use the function geom_line(linetype = ""). I've tried to add the code in the same way as the theme and linesize, but it doesn't work. Example tries of code below:
plot <- plot +theme_bw() + geom_line(size = 1.25) + geom_line(linetype = "dashed")
plot <- plot +theme_bw() + geom_line(size = 1.25) + geom_line(aes(linetype = Condition))
plot <- plot +theme_bw() + geom_line(size = 1.25) + scale_linetype_manual(values=c("twodash", "dotted", "solid"))
I'm not a regular R user so I'm probably missing something pretty obvious. I hope someone can help me out.
In sum, I expected the geom_line(linetype="") argument to change the existing lines in the plot to become the designated types, but they remained unchanged. The theme_() and geom_line(size=) worked similarly so I expected similar results.
Following my comment I tried some things with the emmip helpfile examples.
You can change line size within emmip with linearg = list(size = 1.25)
You can add scale_linetype_manual to the output
Example code:
library(emmeans)
noise.lm = lm(noise ~ size * type * side, data = auto.noise)
emmip(noise.lm, type ~ side * size, CIs = TRUE,
linearg = list(size = 1.25)) +
ggplot2::scale_linetype_manual(values=c("twodash", "dotted"))

more professional scatterplot in R

I want to produce the scatterplots between the first variable of a dataset and all others, e.g. from iris the Sepal.Length with all others. I have created the following:
data <- iris[,c(-5)]
par(mfrow = c(2, 2))
for (i in seq(ncol(data))[-1]) {
plot(
data[, 1],
data[, i],
xlab = colnames(data)[i],
ylab = "Y"
)
lines(lowess(data[,1],data[,i]),col="red")
}
which results in:
Is there any way to make it looks more professional and not so simple??
ggplot2 is great for this type of thing. There are a bunch of themes that can be used to quickly create high quality plots. It also gives you a lot of flexibilty to customize your plot by changing individual elements.
In addition to being able to make the plots pretty, it is very effective at creating the plots in the first place. Here is somewhere to start :
library(tidyverse)
#your example data
data <- iris[, c(-5)]
#pivot_longer rearranges the data in to a long form, which makes it easier to plot
data_def <- pivot_longer(data, -Sepal.Length)
#the data to be plotted
ggplot(data_def, aes(x = Sepal.Length, y = value)) +
#adding the scatter plot (each value is a point)
geom_point() +
#adding a LOESS smoothed line (the default method of smoothing), without the standard error
geom_smooth(se = FALSE, color = "red", size = 0.5) +
#Splits into the three plots based on the measurements and moves the titles underneath the x-axis
facet_wrap( ~ name, scales = "free_y", strip.position = "bottom") +
#Changes the overall look of the plot
theme_classic() +
#Removes elements of the former title (now x-axis) so that there is no surrounding box
theme(strip.background = element_blank(),
strip.placement = "outside") +
#Manually change the axis labels
labs(x = NULL, y = "Y")
I also use ggpubr which is based on ggplot2

ggplot2 produces two legends instead of one

I am trying to do a simple logged ggplot, showing the change in tree and shrub density over time (site age). the tree species are split into native / exotic.
I have also downloaded the viridis package, to enable a type of coloration to the legend+line+points+confidence interval fill.
The problem is, when I do plot using the viridis code, I get two separate legends, which I don't want. I can't figure out how to keep the viridis legend, and remove the other legend.
I would love to provide a picture of my output - but can't figure out how to add it to this question template...
this is the code I have used:
attach(data.df4)
base <- ggplot(data.df4, aes(age, total_trees))
base +
theme_classic(base_size = 10, base_family = "times") +
scale_y_log10() +
geom_point(aes(color = status)) +
geom_smooth(aes(color = status, fill = status), method = "lm", se = TRUE) +
scale_colour_viridis(discrete = TRUE, option = "D")+
scale_fill_viridis(discrete = TRUE, option = "D") +
labs(title = "changes in planted canopy and subcanopy tree and shrub density over time",
x = "planting age",
y = "density (plot-level)")
Without seeing your data or a screenshot, it's hard to know what needs to change. You can remove legends you don't want in 2 different ways
turn off the fill legend ggplot() + guides(fill = FALSE)
specify not to create a legend within the layer geom_smooth(..., show.legend = FALSE)
This article can show you how to post some sample data:
https://reprex.tidyverse.org/articles/articles/datapasta-reprex.html

how to show all data points on y axis in ggplot heatmaps?

I've created a heatmap using ggplot
library(plyr)
library(scales)
guide_ind <- ddply(guide_tag[company == FALSE], .(tag), transform, rescale = rescale(count))
(p <- ggplotly(ggplot(guide_ind, aes(tag, username)) +
geom_tile(aes(fill = rescale),colour = "white") +
scale_fill_gradient(low = "white",high = "steelblue") +
theme(axis.text.x = element_text(angle= 90, hjust=1), legend.position= "bottom") )
)
I have about 700 rows of user name, and I would like to make sure that all the usernames are visible in document so that when I produce this in markdown, it will show the names individually instead of overlapping like the picture below.
I've tried using the fig.height, and gplot heatmap, but neither has worked.
Does anyone have suggestions to how to make all data points visible on the yaxis?

Automatically resizing legend for a plot made using ggplot2 such that the entire legend lies within the boundary of the layer

I have some data here
I read the data into a data frame and then plot this data with this following code,
# Reading data from a .csv file into a data frame
df <- read.table("newcsv_file.csv",header=T,sep="\t" )
# Now melting the data frame prior to plotting
df_mlt <- melt(df, id=names(df)[1], measure=names(df)[c(2, 6, 11,16,21,26,31,36,41,46,51,106,111,116,121,126,131,136,141,146,151)], variable = "cols")
# plotting the data
plt_fit <- ggplot(df_mlt, aes(x=x,y= value, color=cols)) +
geom_point(size=2) +
geom_smooth(method = "lm", se = FALSE) +
scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) +
annotation_logticks(sides = "rl") +
theme_bw() +
theme(legend.text=element_text(size=12), legend.title=element_text(size=12))+
theme(axis.text=element_text(size=14)) +
theme(axis.title=element_text(size=14,face="bold")) +
labs(x = "x", y = "y") +
scale_color_discrete(name = "values", labels = c("0","-0.1","-0.2","-0.3","-0.4","-0.5","-0.6","-0.7","-0.8","-0.9","-1","+0.1","+0.2","+0.3","+0.4","+0.5","+0.6","+0.7","+0.8","+0.9","+1")) +
guides(colour = guide_legend(override.aes = list(size=3),nrow=2,title.position = 'top',title.hjust=0.5,legend.direction = "horizontal")) +
theme(legend.position = 'bottom', legend.margin=unit(1,"cm"),legend.background = element_rect(fill ='gray94')) +
theme(plot.margin=unit(c(0,2,0,0),"mm"))
The resulting plot looks like this, the problem here is that the right most edge of the legend is cropped.
I use +theme(legend.margin=unit(1,"cm")) but this does not seem sufficient. Could someone please let me know what I can change to display the full legend properly in the plot.
Thanks.
The code is fine. The problem is the size of your plot window. Try making it wider and you'll see the whole legend.
Also,
ggsave("plot_fit.pdf",plot_fit)
will create a pdf where the full legend is displayed.
After changing the width and height of the plot using the following code,
ggsave(file="new_png_file.png",width=22,height=21,units=c("cm"), dpi=600)
Yields a plot such as this,

Resources