How to create a legend title in a ggplot2 line graph - r

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

Related

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

Putting error bars on jittered points in R

I'm trying to plot a scatter graph with error bars in R using categorical data on the x axis, using the following code:
Nesk <- read.table("E:\\R stuff\\Chapter 2\\Boxplots of nb\\NEnbNOINF.txt", header=TRUE, fill=TRUE)
pd <- position_dodge(0.2)
ggplot(Nesk, aes(x = TYPE, y = NB, color = TYPE)) +
geom_jitter() +
geom_point(position = pd) +
geom_errorbar(aes(ymin = LC, ymax = UC), position = pd) +
theme_bw() +
theme(axis.title = element_text(face = "bold")) +
ylab("Nb")
However, I can't get the error bars on the jittered points. I end up with this https://imgur.com/qBcvOat. Sorry all, don't have the reputation to directly insert images
I've tried using position dodge however I'm aware that it just separates the points by category (COL, LIN, NOM) as opposed to within each category. Is there any way I can jitter the points and attach error bars to these? I've seen some posts with fixes for this, but I think somewhere along the line an update invalidated those.
Thanks in advance!

How to adjust the following ggplot2 graph?

I conduct a research about global education recently and the following graph is an important plot of my research.
ggplot(sam_data,aes(JOY,PV)) +
geom_line(aes(colour = Individualism))+
facet_grid(occupation~as.factor(Gender)) +
theme(legend.key.height = unit(2.0,"cm"),legend.text = element_text(size = 5,face = "plain")) +
scale_color_continuous("Individualism",labels=sam_data$country,breaks =sam_data$Individualism)+
geom_smooth()
And the problem is obvious :
1) The correlation line of different countries is all combined into one line, instead of different lines when segmented into gender and occupation.
2) The legend is a mess as I want to make it shown clear the countries corresponding to their individualism level. However, I tried to adjust many parameters of the legend and it did not work so much.
3) Also, I do not know how to delete the white gap produced by the breaks parameter. Any thoughts would be great!
I have solved the second problem by adjusting the aes parameter in ggplot function. The new code of mine is as follows
ggplot(sam_data,aes(JOYSCIE,PV1SCIE,group = CNTRYID)) +
geom_point(aes(color = Individualism.comp4))+
facet_grid(recode.OCOD3~as.factor(Gender0women1men)) +
theme(legend.key.height = unit(3.0,"cm"),legend.text = element_text(size = 5,face = "plain")) +
scale_color_gradientn("Individualism",labels=sam_data$CNTRYID,breaks =sam_data$Individualism.comp4,colors = rainbow(4))+
scale_x_continuous(limits = c(-2,2))

R: tailoring legend in ggplot boxplot leaves two separate legends

I have created a faceted boxplot using the ggplot2 package. The R code is as follows:
version.labs <- c(`1`="Version 1.0", `2`="Version 2.0", `3`="Version 3.0", `4`="Version 4.0", `5`="Version 5.0")
ggplot(df, aes(x=factor(Subsystem), y=Risk.value, fill=factor(Version)) ) +
geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Version)), alpha=0.9) +
geom_boxplot(alpha = 0.5, show.legend = FALSE) + facet_grid(.~Version, labeller = as_labeller(version.labs)) +
theme(strip.text.x = element_text(size=9, color="black", face="bold"))
The resulting plot looks pretty good (as shown below) exept for the legend.
In the legend I want to change the title as well as the text label for each item. The title should be "Version" and the labels "Version 1.0", ..., "Version 5.0".
I've tried various ways but they all add a new separate legend. The new legend looks good, but the old one is still there which doesn't look good and I can't find a way to remove it.
The last thing I tried was to add the scale_color_manual() function, like this:
scale_color_manual(name = "Version", labels=c("v1.0","v2.0","v3.0","v4.0","v5.0"), values=c("grey","blue","green","red","black"))
This results in a boxplot that looks like this.
As can be seen there are two legends. So, close but no cigar. Any hints on how to solve this are appreciated.
I figured out the problem. It was that I had placed my aestetic fill function aes() in the general ggplot(). This should instead be placed in geom_boxplot(), otherwise both the general ggplot() as well as the geom_boxplot() will add a legend. So I fixed that, and then I used guides() to update the title in the geom_boxplot() legend. The full code looks as follows:
ggplot(df, aes(x=factor(Subsystem), y=Risk.value) ) +
geom_jitter(position=position_jitter(width=0.3, height=0.2), aes(colour=factor(Version)), alpha=0.9) +
geom_boxplot(alpha = 0.5, show.legend = FALSE, aes(fill=factor(Version))) + facet_grid(.~Version, labeller = as_labeller(version.labs)) +
theme(strip.text.x = element_text(size=9, color="black", face="bold")) +
labs(x="Risk distribution per software version and subsystem type", y="Normalized risk value") +
guides(color=guide_legend("Version"))
The final plot looks like this, which I'm happy with.
You are using fill argument for grouping and generation of legend. may be instead of scale_color_manual you can use scale_fill_manual to override the existing legend

Limit the color variation in R using scale_color_grey

Before I start, allow me to explain my graph: I have two Genotypes (WTB and whd) and each have two conditions (0 and 7), so I have four lines.
Now, I want to make a plot where each variable and its condition is the same color. Anything with whd will be black and anything with WTB will be grey.
I managed to make the graph with the solid/dashed lines correctly, however, I am having trouble with the coloring. I can only make it so that there is a grey gradient. Are there any parameters for scale_color_grey to help me with this?
This is my code (I took out parts of it for easier read):
ggplot(data=df4, aes(x=Day, y=Remain, group=Condition, shape=Condition, colour=Condition) +
theme_bw() +
geom_line(aes(linetype=Condition), size=1) +
geom_point(size=0, fill="#FFFFFF") +
scale_linetype_manual(name="Genotype",
values=c("solid", "dashed", "solid", "dashed")) +
scale_shape_manual(name="Genotype", values=c(1,19,1,19)) +
scale_color_grey(name="Genotype")
I think this code should produce the plot you want. However, without your exact dataset, I had to generate simulated data.
## Generate dummy data and load library
library(ggplot2)
df4 = data.frame(Remain = rep(0:1, times = 4),
Day = rep(1:4, each = 2),
Genotype = rep(c("wtb", "whd"), each = 4),
Condition = rep(c("0", "7"), times = 4 ))
Next, I created a grouping variable:
df4$both = paste0(df4$Genotype, df4$Condition)
And last, I plotted and saved the figure:
example <- ggplot(data=df4, aes(x=Day, y=Remain,
group=both,
color = Genotype,
linetype = Condition)) +
geom_line() +
scale_color_manual(values = c("grey50", "black")) +
scale_linetype_manual(values = c("solid", "dashed")) +
theme_bw()
ggsave("example.jpg", example)
From your code, it was not apparent why you included the geom_point. Also, if you only want one sub-legend, rather than two, this SO question provides details on how to do that.

Resources