Plot can't be displayed in RMarkdown Presentation - r

We've been trying to include a graphic of our plot(s) in the R markdown presentation, but it simply does not work. The code is working and we can see the plot in Rscript and the markdown report, but it doesn't work in the knitted presentation. We used the following code:
Boxplot {#plots .flexbox .vcenter}
a <- boxplot(student$bmi, col = "lightgreen",
main = "BMI allgemein",
col.main = "darkgreen",
ylab = "BMI (in kg/m^2)",
ylim = c(0,40))
a
as well as a ggplot
GGPlot
student %>%
ggplot(aes(x= Bewegung1, y=bmi, fill= Geschlecht)) +
geom_boxplot() +
ggtitle("Geschlechterspezifische Verteilung des BMI in Abhängigkeit von der Bewegung") +
theme(plot.title = element_text(hjust = 0.5)) +
stat_summary(fun = mean, colour = "darkblue", geom = "point",
shape=18, size=3, show.legend = FALSE) +
scale_y_continuous(breaks = seq(0,40, by = 5)) +
labs(x="Selbsteinschätzung der Bewegung in den letzten 7 Tage (60 min/day)", y="BMI")
We've tried adding different libraries (like httpuv) as suggested in other forums, but this doesn't work for us. We added the libraries ggplot2, tidyverse, ggtheme, foreign, dplyr and others (not relevant for this code).
We've also tried adding plot() as well as print() after the code and we've also looked at other presentation where it worked, did the exact same thing, but it didn't work for our presentation.
We're completely lost. Please help.
The output is shown like this

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"))

ggplot only change the font of certain parts in the legend

Is it possible to put the scientific names of the fish in italics on the x-axis and in the legend and to use normal font for the rest?
In my case I would like that for example Barbatula barbatula (Bachschmerle) only Barbatula barbatula is in italics and (Bachscmerle) in the normal font
This is the bar chart right now
And this is a part of the data im using
My code is:
ggplot(R_Sandbach, aes(x = fct_infreq (Species), fill=Species ))+
geom_bar()+
theme_minimal()+
geom_text(aes(label=..count..), stat = "count", vjust = -.1, colour= "black")+
theme(axis.text.x = element_text(angle = 90, size = 5))+
xlab("Fischarten")+
ylab("Individuenanzahl")
ggtext is definitely a good option, although you can just manipulate aspects of your plot directly using theme as you've done in your question.
See an example below:
library(tidyverse)
ggplot() +
geom_blank() +
labs(x = "Fischarten", y = "Individuenanzahl", title = "My Super Awesome Title") +
theme(axis.title.x = element_text(face = "italic"),
plot.title = element_text(face = "italic"))
This produces a blank plot with the plot title and x axis both in italics. You can add as many changes into your theme() function as you like.
EDIT:
In the case of which you need specific words of your titles in italics, etc. you can manually incorporate html into your text and then format your plot to read this html.
In my personal experience this has sometimes caused issues with the general themes of ggplot.
Using this package library(mdthemes) solves the issues of html not being read as it should.
For example:
ggplot() +
geom_blank() +
labs(x = paste("<i>Fischarten</i>", "Other Title Stuff"), y = "Individuenanzahl", title = paste("My Super", "<i>Awesome Title</i>")) +
mdthemes::md_theme_classic()

Legend in R markdown

I can´t figure it out how to fit a legend with a graph in Markdown R.
My result looks like this.
plot_druhych_davek = ockovani %>%
ggplot(aes(x=datum,y=druhych_davek, color = kraj_nazev))+ #+ scale_y_log10()
geom_line(alpha = 0.8)+
labs(title = str_wrap( sprintf("Průběh druhých dávek očkování od: %s DO: %s", OD, DO),40) ,
x = "Datum",
y = "Počet dávek",
color = "kraj_nazev")+
theme_fivethirtyeight()+
theme(axis.title = element_text()) +
theme(legend.title = element_blank())
plot(plot_druhych_davek)
Sadly I dont have enough Rep to put this as a comment but you might be interested in
ggplot(xyz) + scale_color_xxx(guide = guide_legend(keywidth = xxx, keyhight = xxx))
this line of code lets you customize your legend quite granularily, however for me always involves a lot of trial and error. There are much more arguments than the ones I used within guide_legend(). Good luck!

How to create a legend title in a ggplot2 line graph

I am creating a line graph using the ggplot2 package in R.
I cannot upload the data as it is for a study I am conducting for my final year project. So, I can only share the code with you.
This is the code for the APA formatted graph.
ggplot(accuracy_data,
aes(x = eccentricity, y = accuracy, group= speech_task)) +
geom_line(aes(linetype=speech_task)) +
scale_linetype_manual(values=c("twodash", "dotted", "solid")) +
geom_point(aes(shape = speech_task)) +
facet_grid(. ~ duration, labeller=labeller(duration = labels)) +
labs(x='Eccentricity (degrees of visual angle)', y='Accuracy of responses') +
theme_apa() +
theme(text=element_text(family='Times')) +
scale_x_continuous(breaks =c(5, 10, 15)) +
geom_errorbar(aes(ymin = accuracy - acc_sum$se , ymax = accuracy + acc_sum$se ), width=.1)
This produces a graph with a legend without a title, hence I am asking for help in creating a title for the legend.
I have tried a lot of different options however none work. I don't even get an error message.
These are the codes I have tried so far:
legend_title <- "Speech Task"
scale_fill_manual(legend_title,values=c("Conversation", "N-Back", "Silence"))
guides(fill=guide_legend(title="Speech Task"))
scale_fill_discrete(name = "Speech Task",
labels = c("Conversation", "N-Back", "Silence"))
labs(fill="Speech Task")
The following and final code I tried was the only one to produce a change in the graph. However because I have manually changed the point shape as well as line type it caused two legends to be made and only titled the line type legend.
labs(linetype= "Speech Task")
Please can I have some help :)
Seeing no data or final results I'm going on a hunch here.
I suspect you need to name shape and fill legends the same. So something along the lines of
scale_linetype_manual(name = legend_title, values = c("twodash", "dotted", "solid")) +
scale_fill_manual(name = legend_title, values = c("Conversation", "N-Back", "Silence")) +

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

Resources