Remove standard deviation from legend ggplot in R - r

I would like to remove sd bars and mean from legend while keeping them on the main figure. In my case I have this:
And I want something like this:
This is my code:
data_summary <- function(x) {
m <- mean(x)
ymin <- m-std.error(x)
ymax <- m+std.error(x)
return(c(y=m,ymin=ymin,ymax=ymax))
}
a<-ggplot(esto,aes(x= Group, y=value, colour = Group, fill=fluency_test),
pattern_fill = "black",
colour = 'black') +
geom_boxplot(outlier.shape = NA,lwd=1.5) +
guides(colour = "none")+
geom_point(position=position_jitterdodge(),alpha=0.5)+
xlab("Group")+
labs(y = names(features)[[i_feature]])+
theme(axis.text.x = element_text(angle = 45, hjust = 1))+
stat_summary(fun.data=data_summary, color="black",position=position_dodge(width=0.75), size = 1.3)+
scale_shape_manual("Summary Statistics", values=c("Mean"="+"))+
scale_color_manual(values=c("#7CAE00","#F8766D","#00BFC4","#C77CFF"))+
scale_fill_manual(values=c("white","azure3"))+
theme_gray(base_size = 18)+
theme(legend.key.size = unit(2, "cm"),
legend.key.width = unit(1,"cm"),legend.title=element_blank(),panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))

You can prevent the point range from being displayed in the legend by adding show.legend=FALSE to stat_summary.
Using a minimal reprex based on mtcars:
library(ggplot2)
ggplot(mtcars, aes(x = cyl, y = mpg, color = factor(cyl))) +
geom_boxplot() +
stat_summary(color = "black", show.legend = FALSE)
#> No summary function supplied, defaulting to `mean_se()`

Related

How to plot counts stackbar in ggplot2 R?

Dataset contains "two friends" and coded "interaction" (all factors). I want to plot the frequency of type of interactions between two friends using a stacked bar. I tried the following code.
Friend1 <- c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B")
Friend2 <- c("1","1","2","2","1","1","2","2","1","1","2","2","1","1","2","2")
Interaction <- c("O","X","D","D","D","X","X","D/R","O","X","D","D","D","X","X","D/R")
df <- data.frame(Friend1, Friend2, Interaction)
df$Friend1 <- as.factor(as.character(df$Friend1))
df$Friend2 <- as.factor(as.character(df$Friend2))
df$Interaction <- as.factor(as.character(df$Interaction))
ggplot(df, aes(fill=Interaction, y=count(Interaction), x=Friend2)) +
geom_bar(position="fill", stat="identity", color = "white") + theme_classic() + theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size=1)) + theme(strip.background = element_blank()) + facet_grid(.~Friend1)
Erorr: Error in UseMethod("count") :
no applicable method for 'count' applied to an object of class "character"
How do I "count" these factors to visualize frequency of interactions?
The issue is that dplyr::count expects a dataframe as its first argument and returns a dataframe. However, there is no reason to compute the counts as geom_bar will do that by default, i.e. get rid of y=... and stat="identity":
library(ggplot2)
ggplot(df, aes(fill = Interaction, x = Friend2)) +
geom_bar(position = "fill", color = "white") +
theme_classic() +
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(colour = "black", size = 1)
) +
theme(strip.background = element_blank()) +
facet_grid(. ~ Friend1)
An alternative visualization using facets per "friends" column may make your counts clearer than a standard stacked bar:
ggplot(df, aes(x = 1, fill = Interaction)) +
geom_bar(width = 1, color = "white", size = 1, alpha = 0.8) +
geom_text(stat = "count", aes(label = after_stat(count)), size = 7,
position = position_stack(vjust = 0.5), color = "white",
fontface = 2) +
facet_grid(Friend1 ~ Friend2, switch = "both") +
scale_fill_brewer(palette = "Set1") +
coord_polar(theta = "y") +
labs(x = "Friend1", y = "Friend2") +
theme_bw(base_size = 20) +
theme(panel.grid = element_blank(),
strip.background = element_blank(),
strip.placement = "outside",
axis.text.x = element_blank(),
panel.border = element_rect(color = "gray90", fill = NA),
panel.spacing = unit(0, "mm"),
axis.text = element_blank(),
axis.ticks = element_blank())

Can you shift the position of a facet label or strip bar in ggplot?

I'm using ggplot to graph a forest plot. I have used facet labels to label groups (in example below Test1, Test2, Test3). Is there a way to slightly shift the actual position of the facet label/strip to the left (as indicated by the arrows in my picture below)?
I can shift the position of the text within the facet label but I think I have done that as much as possible. Thus, I think I need to shift the actual facet label (strip bar/rectangle) itself. Is this possible?
Would be very grateful if anyone could help me or point out a way to get a similar effect!
Please find reproducible code here:
library(dplyr)
library(ggplot2)
library(ggforce)
library(tidyverse)
# Reproducible dataset
df <- data.frame(outcome = c('outcome1', 'outcome1', 'outcome2','outcome2','outcome3','outcome3','outcome4','outcome4','outcome5','outcome5'),
type = c('Test1','Test1','Test2','Test2', 'Test3', 'Test3', 'Test3','Test3', 'Test3', 'Test3'),
Coef = c(0.10026935, 0.10026935, 0.13713358, 0.13713358,0.07753188,0.07753188,0.09193794,0.09193794,0.06170916,0.06170916),
CIr_low = c(0.070955475,0.070955475,0.108705781,0.108705781,0.052595474,0.052595474,0.056340327,0.056340327,0.036185918,0.036185918),
CIr_high = c(0.12958323,0.12958323,0.16556139,0.16556139,0.10246828,0.10246828,0.12753555,0.12753555,0.08723240,0.08723240),
model = c(1,2,1,2,1,2,1,2,1,2))
# Set type as factor
df <- df %>% mutate(type = fct_relevel(type, "Test1","Test2","Test3"))
# Plot with ggplot
ggplot(df, aes(x = outcome, y = Coef, ymin = CIr_low,ymax =CIr_high,fill = as.factor(type))) +
geom_errorbar(aes(x= outcome, ymin=CIr_low, ymax=CIr_high), width=0.2,cex=0.5)+
geom_point(shape = 18, size = 5)+
facet_grid(type ~ ., scales = "free", space = "free") +
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(limits = c(-0.1, 0.25)) +
ggforce::facet_col(facets = type ~ ., scales = "free_y", space = "free", strip.position = "top")+
theme_bw()+
coord_flip() +
xlab('Group')+
ylab(expression("Standardized" ~ beta *" (95%CI)"))+
theme(line = element_line(colour = "black", size = 0.5),
plot.margin = margin(0.5, 0.5, 0.5, 0.5, unit = "cm"),
strip.background = element_rect(colour = "white", fill="white"),
strip.text = element_text(colour = "black",face="italic"),
strip.text.x = element_text(size = 12,angle = 0,hjust = 0,face="bold.italic", color="darkblue"),
legend.position ="none",
axis.line.x = element_line(colour = "black"),
axis.line.y = element_blank(),
panel.border= element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.spacing = unit(2, "lines"),
axis.ticks = element_blank(),
axis.title.x = element_text(colour = "black"),
axis.title.y = element_blank(),
axis.text=element_text( color = "black")
)
You can try:
ggplot(df, aes(x = outcome, y = Coef, ymin = CIr_low,ymax =CIr_high,fill = as.factor(type))) +
geom_errorbar(aes(x= outcome, ymin=CIr_low, ymax=CIr_high), width=0.2,cex=0.5)+
geom_point(shape = 18, size = 5, show.legend = F)+
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(expression("Standardized" ~ beta *" (95%CI)"),limits = c(-0.1, 0.25)) +
xlab("")+
coord_flip() +
facet_grid(type~., scales = "free", space = "free_y", switch = "y") +
theme_minimal() +
theme(strip.placement = "outside",
strip.text.y.left = element_text(angle = 0,vjust = 1,size=12))
Or use a cowplot approach with ggtitle
plots <- df %>%
split(.$type) %>%
map2(.,names(.), ~ggplot(.x, aes(x = outcome, y = Coef, ymin = CIr_low,ymax =CIr_high,fill = as.factor(type))) +
geom_errorbar(aes(x= outcome, ymin=CIr_low, ymax=CIr_high), width=0.2, size=0.5)+
geom_point(shape = 18, size = 5, show.legend = F)+
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(limits = c(-0.1, 0.25))+
coord_flip() +
xlab('')+
ylab(expression("Standardized" ~ beta *" (95%CI)"))+
ggtitle(.y)+
theme_minimal(base_size = 12)+
theme( panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title.position = "plot"))
cowplot::plot_grid(plots$Test1 + theme(axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank()),
plots$Test2 + theme(axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank()),
plots$Test3, ncol = 1)

Changing the figure legend to indicate the line type... (ggplot2)

I have the formula below:
ggplot(Errortrialsmodifyoriginal, aes(x = Target, y = Absolutefirststoperror, color = as.character(Type), shape = as.character(Type))) +
geom_point(shape=16)+
geom_point(data=Errortrialoriginal,shape=19,size = 4,mapping=aes(x=Target, y=Absolutefirststoperror)) +
geom_line(data=Errortrialoriginal,aes(group=Type,linetype=Type),size=2,) +
scale_color_manual(name = "Condition", values = c("red","green","blue","red","green","blue")) +
scale_linetype_manual(name = "Condition",values = c("dashed","dashed","dashed","solid","solid","solid")) +
geom_errorbar(data=Errortrialoriginal,mapping=aes(x=Target, ymin=Absolutefirststoperror-SE,ymax=Absolutefirststoperror+SE),size=0.5) +
theme_bw() + guides(color = guide_legend("Condition"), shape = guide_legend("Condition"), linetype = guide_legend("Condition")) +
labs(x = "Target distance (vm)", y = "Absolute error in stop location (vm)") +
theme(axis.title.x = element_text(size=14, face="bold"), axis.title.y = element_text(size=14, face="bold"),legend.text=element_text(size=14),title=element_text(size=14,face="bold"), plot.title = element_text(hjust = 0.5), legend.title = element_text(size=14,face="bold"), axis.text.x=element_text(size=14),axis.text.y=element_text(size=14),panel.grid.major = element_blank(), panel.grid.minor = element_blank())
Which produces the graph:
How can I change my command to ensure that the dashed and solid lines are shown in the figure legend; because at the moment, the figure legend suggests that all the lines are solid, even though they are not?
I would be grateful for any advice!
To my opinion, the legend is correctly displayed but you can't see it because you have big points front of the linetype. You should increase the legend box to see it.
Here an example with this dummy example:
library(ggplot2)
ggplot(my_data, aes(x = dose, y = length, color = supp, linetype = supp))+
geom_line()+
geom_point(size = 4)
library(ggplot2)
ggplot(my_data, aes(x = dose, y = length, color = supp, linetype = supp))+
geom_line()+
geom_point(size = 4)+
theme(legend.key.size = unit(3,"line"))
So, with your code, you can do something like that:
library(ggplot2)
ggplot(Errortrialsmodifyoriginal,
aes(x = Target,
y = Absolutefirststoperror,
color = Type)) +
geom_point()+
geom_line(data=Errortrialoriginal,
aes(group=Type,
linetype=Type)) +
scale_color_manual(name = "Condition", values = rep(c("red","green","blue"),2)) +
scale_linetype_manual(name = "Condition",values = rep(c("dashed","solid"),each =3)) +
geom_errorbar(data=Errortrialoriginal,
mapping=aes(x=Target,
ymin=Absolutefirststoperror-SE,
ymax=Absolutefirststoperror+SE),size=0.5) +
theme_bw() +
guides(color = guide_legend("Condition"), shape = guide_legend("Condition"), linetype = guide_legend("Condition")) +
labs(x = "Target distance (vm)", y = "Absolute error in stop location (vm)") +
theme(axis.title.x = element_text(size=14, face="bold"),
axis.title.y = element_text(size=14, face="bold"),
legend.text=element_text(size=14),
title=element_text(size=14,face="bold"),
plot.title = element_text(hjust = 0.5),
legend.title = element_text(size=14,face="bold"),
axis.text.x=element_text(size=14),
axis.text.y=element_text(size=14),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.key.size = unit(3,"line"))
Does it answer your question ?
If not, please consider providing a reproducible example of your dataset (see: How to make a great R reproducible example)

My grouped Cross bars DON'T dodge, while my Box plots DO

I want my Crossbars to dodge as well, like my boxplots do, in my example it didn't work, any one can explain what i'm doing wrong or fix my code? I used mtcars as an example and included the result as a picture in which my Crossbars DON'T dodge.
library(ggplot2)
mtcars$am = factor(mtcars$am)
mtcars$vs = factor(mtcars$vs)
cleanup = theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"),
legend.key = element_rect(fill = "white"),
text = element_text(size = 10))
p = ggplot(data = mtcars, aes(x = am , y = mpg, colour = vs)) +
geom_boxplot(aes(colour = vs)) +
stat_summary(aes(colour = vs),
fun.data = "mean_cl_normal",
geom = "crossbar",
position = position_dodge(width = 0.90),
width = .2,
col = "red")
p +
cleanup +
xlab("AM") +
ylab("Miles per Gallon") +
scale_colour_manual(name = "VS",
values = c("Light Gray",
"Dark Grey"))
Which gave me this Graph:
The reason is simple: Specifying col = "red" overwrites the aes mapping to color. There is actually only one group for the crossbars and thus nothing to dodge.
You can fix this by mapping to group:
ggplot(mtcars, aes(x = am , y = mpg, colour = vs)) +
#geom_boxplot() +
stat_summary(aes(group = vs),
fun.data = "mean_cl_normal",
geom = "crossbar",
position = position_dodge(width = 0.9),
width = .2,
col = "red")
However, discarding a color scale only for the crossbars obviously doesn't result in a good plot.

Remove fill around legend key in ggplot

I would like to remove the gray rectangle around the legend. I have tried various methods but none have worked.
ggtheme <-
theme(
axis.text.x = element_text(colour='black'),
axis.text.y = element_text(colour='black'),
panel.background = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.border = element_rect(colour='black', fill=NA),
strip.background = element_blank(),
legend.justification = c(0, 1),
legend.position = c(0, 1),
legend.background = element_rect(colour = NA),
legend.key = element_rect(colour = "white", fill = NA),
legend.title = element_blank()
)
colors <- c("red", "blue")
df <- data.frame(year = c(1:10), value = c(10:19), gender = rep(c("male","female"),each=5))
ggplot(df, aes(x = year, y = value)) + geom_point(aes(colour=gender)) +
stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1,
aes(group = gender, colour=gender)) +
ggtheme + scale_color_manual(values = colors)
You get this grey color inside legend keys because you use stat_smooth() that as default makes also confidence interval around the line with some fill (grey if fill= isn't used inside the aes()).
One solution is to set se=FALSE for stat_smooth() if you don't need the confidence intervals.
+stat_smooth(method = "loess", formula = y ~ x, level=0, size = 1,
aes(group = gender, colour=gender),se=FALSE)
Another solution is to use the function guides() and override.aes= to remove fill from the legend but keep confidence intervals around lines.
+ guides(color=guide_legend(override.aes=list(fill=NA)))
theme_set(theme_gray() + theme(legend.key=element_blank()))
If you want also to remove grey background:
theme_set(theme_bw() + theme(legend.key=element_blank()))
+ theme(legend.background=element_blank())

Resources