Cannot italicize facet labels with labeller = label_parsed - r

I have a ggplot
s = ggplot(final, aes(y = avg,x=factor(dose),fill = factor(mo))) +
facet_grid(.~gene, labeller = label_parsed) +
geom_bar(position = "dodge", stat = "identity", color = "black")
where final is a data.frame containing 4 columns: mo, dose, gene and avg.
I've been trying to italicize the facet labels with
s + theme(strip.text.x = element_text(face = "italic", size = 10, colour = "white"))
to no avail. Size and colour can be changed with no problems.
However, once I remove "labeller" argument from facet_grid(), the font face can be changed accordingly. Is this a bug?
Although I'll work around this problem by setting them individually as suggested here, I'm sure theme() was there for a very good reason.

As you said, you need something like what has been shown here
In fact you have to change directly your levels with italic()
then you use labeller=label_parsed in ggplot
an example:
factor1=rep(letters[1:3], each=3)
factor2=rep(1:3,times=3)
x=rep(1,9)
y=1:9
df=cbind.data.frame(factor1,factor2,x,y)
i revalue the levels:
levels(df$factor1)= c("a"=expression(paste("factor_", italic("a"))),
"b"=expression(paste("factor_", italic("b"))),
"c"=expression(paste("factor_", italic("c"))))
And adapt ggplot:
ggplot(df, aes(x=x, y=x))+facet_grid(factor2~factor1, labeller=label_parsed)+geom_point()

Related

ggplot2 unable to color legend icons

I'm trying to use ggplot2 to make some sort of timeline using values from a dataframe (df). I've managed to plot the data exactly how I want it (the different colored line segments connecting the x-marks in this exact order, i.e., from left to right: 'early', 'unknown', 'late', 'sub'). The startpoint and endpoint columns in the dataframe are used to define the positions of the points and line segments.
The problem is that the legend doesn't show the color of the 'x' icons, they are just grey. I've tried adding scale_color_manual() and scale_fill_manual() commands but they don't seem to change anything. The legend does display the correct color when I change the shape to shape = 21, however, I really want the shape to be 4 (x icons). I don't care about the shape of the legend though but scale_shape_manual() again didn't change anything about the legend.
I have also tried placing different color arguments inside and outside the aes() argument of ggplot(), geom_segment() and/or geom_point().
How can I make the icons from the legend show the correct color?
Below I added a piece of code to reproduce the problem.
library(ggplot2)
library(RColorBrewer)
## Define dataframe
df <- data.frame(Var = c("sub","late","unknown","early"),
Time = c(10,267,0,1256),
Endpoint = c(1533,1523,1256,1256),
Startpoint = c(1523,1256,1256,0))
colorscheme <- RColorBrewer::brewer.pal(9, "Set1")[c(1,4,2,3)]
## Make plot
ggplot(df, aes(x="", y=Endpoint, fill=Var), color =colorscheme) +
geom_segment( aes(x="", xend="", y=Startpoint, yend=Endpoint), color = colorscheme) +
geom_point(aes(x="", y=Endpoint),size=5, shape=4 , color = colorscheme) +
coord_flip()
Thanks in advance for any suggestions!
You should use color instead of fill. To remove the line from the legend, use guides(color = guide_legend(override.aes = list(linetype = 0))) or use show.legend = F in geom_segment.
Also, arguments passed in ggplot need not to be repeated afterward.
ggplot(df, aes(x="", y=Endpoint, color=Var), colorscheme) +
geom_segment(aes(xend="", y=Startpoint, yend=Endpoint)) +
geom_point(size=5, shape=4) +
coord_flip() +
guides(color = guide_legend(override.aes = list(linetype = 0)))
#or
ggplot(df, aes(x="", y=Endpoint, color=Var), colorscheme) +
geom_segment(aes(xend="", y=Startpoint, yend=Endpoint)) +
geom_point(size=5, shape=4) +
coord_flip()
Try this:
ggplot(df, aes(x = "", y = Endpoint, color = Var), colorscheme) +
geom_segment(aes(x = "", xend = "", y = Startpoint, yend = Endpoint), show.legend = FALSE) +
geom_point(aes(x = "", y = Endpoint), size = 5, shape = 4) +
coord_flip()
In this way legend will show only X

How to change colour of histograms with facet_grid and the position of the text?

How can I change the colour for the two histograms plot made with facet_grid?
I would like to have the histogram of "Active" in green and "Failed" in red.
And also, how can I change the position of the text of the line in order to have it a bit more down?
Here is my code:
df %>%
ggplot(aes(x = `Banks/turnover%Last avail. yr`)) +
geom_histogram(
bins = nclass.Sturges(`Banks/turnover%Last avail. yr`),colour = "black")+
geom_vline(data = status_means, aes(xintercept = avg), color="red", linetype="dashed")+
geom_text(data = status_means , aes(x = avg, label = avg), y= Inf )+
theme(legend.position="None")+
facet_grid(~general_status)
You need to add a factor to the fill parameter. Here, I just use active-failed as I'm not sure how you have that distinguished in your data.
ggplot(df_all,
aes(x = `Banks/turnover%Last avail. yr`, fill = as.factor(active-failed)))
Then, you can add a line to define the colors:
scale_fill_manual(values = c("green", "red"))
As #teunbrand said, you can just use vjust to move the text so that it is not cut off.
Remember to give a good reproducible example, it is helpful to provide some of your data via dput(head(df)).

Stat summary for each factor in scatter plot ggplot2: What about fun.x, fun_y combinations?

I have a bunch of data for people touching bacteria for up to 5 touches. I'm comparing how much they pick up with and without gloves. I'd like to plot the mean by the factor NumberContacts and colour it red. E.g. the red dots on the following graphs.
So far I have:
require(tidyverse)
require(reshape2)
Make some data
df<-data.frame(Yes=rnorm(n=100),
No=rnorm(n=100),
NumberContacts=factor(rep(1:5, each=20)))
Calculate the mean for each group= NumberContacts
centroids<-aggregate(data=melt(df,id.vars ="NumberContacts"),value~NumberContacts+variable,mean)
Get them into two columns
centYes<-subset(centroids, variable=="Yes",select=c("NumberContacts","value"))
centNo<-subset(centroids, variable=="No",select="value")
centroids<-cbind(centYes,centNo)
colnames(centroids)<-c("NumberContacts","Gloved","Ungloved")
Make an ugly plot.
ggplot(df,aes(x=gloves,y=ungloved)+
geom_point()+
geom_abline(slope=1,linetype=2)+
stat_ellipse(type="norm",linetype=2,level=0.975)+
geom_point(data=centroids,size=5,color='red')+
#stat_summary(fun.y="mean",colour="red")+ doesn't work
facet_wrap(~NumberContacts,nrow=2)+
theme_classic()
Is there a more elegant way by using stat_summary? Also How can I change the look of the boxes at the top of my graphs?
stat_summary is not an option because (see ?stat_summary):
stat_summary operates on unique x
That is, while we can take a mean of y, x remains fixed. But we may do something else that is very concise:
ggplot(df, aes(x = Yes, y = No, group = NumberContacts)) +
geom_point() + geom_abline(slope = 1, linetype = 2)+
stat_ellipse(type = "norm", linetype = 2, level = 0.975)+
geom_point(data = df %>% group_by(NumberContacts) %>% summarise_all(mean), size = 5, color = "red")+
facet_wrap(~ NumberContacts, nrow = 2) + theme_classic() +
theme(strip.background = element_rect(fill = "black"),
strip.text = element_text(color = "white"))
which also shows that to modify the boxes above you want to look at strip elements of theme.

ggplot2 custom legend combining shape and fill

I am trying to combine fill and color in a ggplot2 legend. Because there are several colors for the x axis, it seems logic that ggplot2 do not know which color to pick in the legend.
For exemple:
library(ggplot2)
ggplot(mpg, aes(fl, hwy)) +
geom_point(aes(color = fl, shape = factor(year), fill = fl)) +
scale_shape_manual(values = c("circle filled", "circle open"))
My goal would be to manually edit the factor(year) legend to look like this:
I played around the guides() function without success.
Edit:
Values for shape can be found by running vignette("ggplot2-specs").
you already had the nearly correct answer with the scale_shape_manual. But somehow the "circle filled" argument is invalid. Since i'm not sure where those values can be looked up, i took the values from a table of a similar question (source):
so with value 20 and 79 you can get the desired result.
ggplot(mpg, aes(fl, hwy)) +
geom_point(aes(color = fl, shape = factor(year), fill = fl)) +
scale_shape_manual(values = c(16,79))
output:
Ok, so here is a very roundabout way of making it look like the image above. Maybe someone else can come up with a more intuitive version:
ggplot(mpg, aes(fl, hwy)) +
geom_point(aes(color = fl, shape = factor(year), fill = factor(year))) +
scale_shape_manual(values = c(16,79), guide = FALSE) +
scale_fill_manual("Year", values=c("grey","white"))+
guides(fill = guide_legend(override.aes = list(shape = c(21,21),
color = c("black", "black"))))
Output:

Change outline and fill colors of histogram with qplot

I have two histograms in one window (using facet) and I would like control over the color of the outline and the fill. I've tried looking up color scales, aes(), + color, + fill, including color and fill in qplot, all resulting in expected plots!
My code can be found below. (Note: mussel2 has two columns concentration (a list of numbers) and waterbody (listed or reference). I can provide the data if necessary.
I understand this is an elementary question, so I do appreciate your time.
qplot(data=mussel2,
x = Concentration,
xlim = x_lim,
ylim = y_lim,
xlab = expression(paste("Concentrations of DDE (", mu, "g/g)")),
ylab = "Frequency",
binwidth = 1.5)+
theme(legend.position="none")+
facet_grid(Waterbody~.)
If you want to keep the qplot format, try the following:
library(ggplot2)
qplot(diamonds$carat,
xlab="Carat",
geom="histogram",
ylab="Count",
binwidth=0.25,
fill=I("grey"),
col=I("black"))
Use ggplot if you want to tweak things. I left out some of your options, but you can probably work out how to put them in.
ggplot(data = mussel2, aes(x = Concentration)) +
geom_bar(binwidth = 1.5, fill = "firebrick4", color = "dodgerblue2") +
scale_x_continuous(limits = x_lim) +
labs(y = "Frequency") +
facet_wrap(~ Waterbody)

Resources