how to show all mean values in the boxplot with ggplot2? [duplicate] - r

This question already has answers here:
Add mean to grouped box plot in R with ggplot2
(2 answers)
Closed 1 year ago.
I am trying to add the mean values (as shown in red dots in the plot below) in the boxplot with ggplot2. I used stat_summary to add mean values.
However, the following plot is not the exact one that I am looking for. What I'd like to get is to show two mean values for both Y (blue box) and N (red box), not one mean value for both.
Here is my code.
ggplot(data = df.08.long,
aes(x = TMT_signals, y = as.numeric(TMT_Intensities), fill = `probe.Mod.or.not(Y/N)`)) +
geom_boxplot() +
stat_summary(fun.y=mean, geom="point", shape=20, size=5, color="red", fill="red") +
coord_cartesian(
xlim = NULL,
ylim = c(0, 2e4),
expand = TRUE,
default = FALSE,
clip = "on")
theme_classic() +
theme(axis.title=element_text(size=8),
axis.text=element_text(size=10),
axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
Does anyone know how to solve this problem?
Thanks so much for any help!

mtcars example
Code
mtcars %>%
ggplot(aes(as.factor(vs),drat, fill = as.factor(am)))+
geom_boxplot()+
stat_summary(
fun=mean,
geom="point",
shape=21,
size=5,
#Define the aesthetic inside stat_summary
aes(fill = as.factor(am)),
position = position_dodge2(width = .75),
show.legend = FALSE
)
Output

Related

How to recreate this plot in ggplot2? [duplicate]

This question already has an answer here:
Barplot in ggplot
(1 answer)
Closed 1 year ago.
Here is my data and original plot:
z <- dbinom(0:6, size=6, p=0.512)
names(z) <- as.character(0:6)
barplot(z, space=0, ylab="Probability", col = "firebrick", las = 1, xlab = "Number of boys")
I need to recreate this same plot in ggplot2 but I'm struggling to make it look remotely similar. Any help would be appreciated.
Building on your code:
library(ggplot2)
ggplot(data.frame(z = z, num_boys = names(z)), aes(x = num_boys, y = z)) +
geom_bar(stat = "identity", fill = "firebrick", col = "black", width = 1) +
labs(y = "Probability", x = "Number of boys") +
ggthemes::theme_base()
NOTE: I used ggthemes::theme_base() to make the plot look like the base plot your original code produces.
If you want to add some customization of axis and background :
z=as.data.frame(z)
colnames(z)=c("Probability")
z$`Number of boys`=rownames(z)
my_theme= list(theme_bw(),
theme(panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),axis.ticks.x = element_blank(),axis.line.x=element_blank()))
ggplot(z, aes(`Number of boys`,Probability)) +
geom_bar(stat = "identity",width = 1,color="black",fill="firebrick")+
my_theme +
annotate(x=0,xend=0,y=0, yend=0.4, colour="black", lwd=0.75, geom="segment")

Order data on ggplot [duplicate]

This question already has answers here:
Reorder bars in geom_bar ggplot2 by value
(3 answers)
Closed 3 years ago.
I currently have a ggplot however it is shown in alphabetical order, I want the graph to show the most 'important score' first and order in descending order. See image of plot attached and code.
library(ggplot2)
ggplot(data= VIMP, aes(x=(VIMP$Y),y=VIMP$X)) +
geom_bar(position="dodge",stat="identity",width = 0, color =
"black") +
coord_flip() + geom_point(color='skyblue') +
xlab("Variables")+ylab(" Importance Score")+
ggtitle("Variable Importance") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(panel.background = element_rect(fill = 'white', colour =
'black'))
To solve this problem you might use the library(forcats) package. Forcats is a package that was made to deal with factors in R.
This code might work for you.
VIMP <- VIMP %>%
mutate(Y = forcats::fct_reorder(Y, X)) ##reorder the Y variable based on X, it's also possible to change to a descending order using desc(X).
ggplot(data= VIMP, aes(x=(VIMP$Y),y=VIMP$X)) +
geom_bar(position="dodge",stat="identity",width = 0, color =
"black") +
coord_flip() + geom_point(color='skyblue') +
xlab("Variables")+ylab(" Importance Score")+
ggtitle("Variable Importance") +
theme(plot.title = element_text(hjust = 0.5)) +
theme(panel.background = element_rect(fill = 'white', colour = 'black'))

Removing "a" symbol from colour legend in ggplot2 [duplicate]

This question already has answers here:
Remove 'a' from legend when using aesthetics and geom_text
(6 answers)
Closed 5 years ago.
I keep getting this a on my colour legend when I make this graph in GGPLOT2.
ggplot(sher_ei_si, aes(SI, EI, shape = crop, label = treatment, colour =
management)) +
geom_point() +
geom_text_repel(aes(SI, EI)) +
xlim(0, 100) +
ylim(0, 100) +
labs(x = "Structure", y = "Enrichment", shape = "Crop", colour =
"Management") +
geom_vline(xintercept = 50) +
geom_hline(yintercept = 50) +
scale_colour_manual(values = c("grey0", "grey60")
Plot showing a under colour legend
For exact output generation, please provide the input data.
You can use show.legend = FALSE to exclude the a symbol from your example:
geom_text_repel(aes(SI, EI), show.legend = FALSE)

Cowplot: How to add tick marks and corresponding data labels to a marginal plot? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
R Packages: cowplot / ggplot2
Use Case: Scatter plot with marginal histograms.
Issue: For histograms, I can't add bin sizes or reference lower/ upper
class intervals in the x-axis. Without these histograms are difficult
to read.
In cowplot, is there any way to add tick marks and corresponding data
labels (in x-axis) to marginal plots, when required? E.g. for
histograms in marginal plots
Basic scatter + marginal histogram plot using cowplot
require(ggplot2)
require(cowplot)
Main Plot:
pmain <- ggplot(data = mpg, aes(x = cty, y = hwy)) +
geom_point() +
xlab("City driving") +
ylab("Highway driving") +
theme_grey()
Marginal plot:
xbox <- axis_canvas(pmain, axis = "x") +
geom_histogram(
data = mpg,
aes(x = cty),
colour = "black"
)
Combined Plot:
p1 <- insert_xaxis_grob(pmain, xbox, grid::unit(0.5, "in"), position = "top")
ggdraw(p1)
However, I'd want the following plot xbox2 to be displayed as x-axis marginal plot:
xbox2.1 <- ggplot() +
geom_histogram(
data = mpg,
aes(x = cty),
colour = "black"
)
hist_tab <- ggplot_build(xbox2.1)$data[[1]]
xbox2 <- xbox2.1 +
scale_x_continuous(
breaks = c(round(hist_tab$xmin,1),
round(hist_tab$xmax[length(hist_tab$xmax)],1))
) +
labs(x = NULL, y = NULL) +
theme(
axis.text.x = element_text(angle = 90, size=7,vjust=0.5),
axis.line = element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)
xbox2
But I can't create a scatter + marginal histogram (xbox2). I get the same plot as the first one:
p2 <- insert_xaxis_grob(pmain, xbox2, grid::unit(0.5, "in"), position = "top")
ggdraw(p2)
Package author here. What you're seeing is the documented behavior. From the documentation of the grob argument of insert_xaxis_grob():
The grob to insert. This will generally have been obtained via get_panel() from a ggplot2 object, in particular one generated with axis_canvas(). If a ggplot2 plot is provided instead of a grob, then get_panel() is called to extract the panel grob.
This function is specifically not meant to stack plots. You could turn your entire plot into a grob and then insert using this function, but I'm not sure that makes a lot of sense. What you're trying to do is equivalent to stacking two plots with the same x-axis range. I think it's better to just code it like that explicitly.
library(cowplot)
xlimits <- c(6, 38)
pmain <- ggplot(data = mpg, aes(x = cty, y = hwy)) +
geom_point() +
xlab("City driving") +
ylab("Highway driving") +
scale_x_continuous(limits = xlimits, expand = c(0, 0)) +
theme_grey() +
theme(plot.margin = margin(0, 5.5, 5.5, 5.5))
xhist <- ggplot() +
geom_histogram(
data = mpg,
aes(x = cty),
colour = "black",
binwidth = 1,
center = 10
) +
scale_x_continuous(limits = xlimits, expand = c(0, 0), breaks = 8:35) +
labs(x = NULL, y = NULL) +
theme(
axis.text.x = element_text(angle = 90, size=7, vjust=0.5),
axis.line = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
plot.margin = margin(5.5, 5.5, 0, 5.5)
)
plot_grid(xhist, pmain, ncol = 1, align = "v", rel_heights = c(0.2, 1))

Why ggplot2 legend not show in the graph [duplicate]

This question already has answers here:
Add legend to ggplot2 line plot
(4 answers)
Closed 2 years ago.
I use ggplot to scatterplot 2 datasets and want to show the legend in the top left. I tried some code but didn't work. I am not sure why this happened.
ggplot(mf, aes(log10(mf[,2]),mf[,1]))
+ ggtitle("Plot")
+ geom_point(color = "blue") + theme(plot.margin = unit(c(1,2,1,1), "cm"))
+ xlab("xxx") + ylab("yyy")
+ theme(plot.title = element_text(size=18,hjust = 0.5, vjust=4))
+ geom_point(data=mf2,aes(log10(mf2[,2]),mf2[,1]),color="red")
+ theme(axis.title.x = element_text(size = rel(1.3)))
+ theme(axis.title.y = element_text(size = rel(1.3)))
+ scale_color_discrete(name = "Dataset",labels = c("Dataset 1", "Dataset 2"))
Since values were not provided, I have used my own values for the demonstration purpose.
mf is a dataframe with log and val as it's column.
You need to put the color parameter inside the aesthetics. This will result in the mapping of colors for the legend. After that you can manually scale the color to get any color you desire.
you can use the below code to get the desired result.
ggplot(mf, aes(val,log))+
geom_point(aes(color = "Dataset1"))+
geom_point(data=mf2,aes(color="Dataset2"))+
labs(colour="Datasets",x="xxx",y="yyy")+
theme(legend.position = c(0, 1),legend.justification = c(0, 1))+
scale_color_manual(values = c("blue","red"))

Resources