I am trying to label the y-axis of my graph with the Theta greek symbol and P(z) with a comma separating them. Additionally, I am tyring to label my x-axis Q(z_i) where i is a subscript. I have tried to do this a few different ways..
string <- ", P(z)"
thet <- bquote(theta)
ylab.fig2 <- paste(thet, string, sep = "")
and have done something similar with expression(theta). I use ylab.fig2 as an input in my ggplot, ylab(fig.2).
new <- ggplot(data = data.frame(x=0), aes(x=x)) +
stat_function(fun=Pz.eq, aes(colour="P(z)")) +
stat_function(fun=bid1, aes(colour="Bid Curve: House 1")) +
stat_function(fun=bid2, aes(colour="Bid Curve: House 2")) +
stat_function(fun=bid3, aes(colour="Bid Curve: House 3")) +
xlim(0,20) + ylim(0,6) +
xlab("Q(z_i)") + ylab(ylab.fig2) +
ggtitle("Figure 2: Property Choice Per Household") +
theme(panel.grid = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
legend.title = element_blank(),
plot.title = element_text(hjust=0.5)) +
scale_colour_manual("Groups",
values = c("darkseagreen", "darkkhaki", "darkslategray3", "firebrick"))
The bquote() and expression() both work fine if they are sole inputs but when I use paste to return the rest of the axis label the greek symbol is not output. I believe this is due to the differing class() of each object. Alternatively, if there is a way to compile LaTex in the labels that would solve both my x and y-axis issues.
This is what my graph looks like thus far...
Overall, there are three things I'm trying to accomplish with x and y-axis labels:
1) Concat greek letters with text.
2) Put bold text inside of the label (only the z vector in P(z) will be bold).
3) Place 'i' subscripts on my text.
While the question regarding Greek letters has been posted before I am looking for a solution using LaTex where I can use more than just math symbols. Using LaTex code is will allow me to solve issues 2 and 3, not just 1.
The latex2exp package is probably the easiest:
library(latex2exp)
string <- ", P(z)"
thet <- "$\\theta$"
ylab.fig2 <- TeX(paste(thet, string, sep = ""))
And then use as ... + ylab(ylab.fig2) to build the plot.
Or using bquote and expression:
library(ggplot2)
i=2
f <- bquote(expression(theta * ", " * P(bold(z))))
g <- bquote(expression(Q(z[.(i)])))
ggplot(mtcars, aes(x=hp, y=wt)) + geom_point()+
ylab(eval(f))+
xlab(eval(g))
Related
With ggplot, I want to add a left aligned legend title with multiple lines and exponents in the text for the units of the values in the legend. I'm plotting data of a form similar to:
leakage_rates_levels <- c(5.4, 0.25)
leakage_rates <- as.factor(rep(leakage_rates_levels, 3)) # L/s-m^2 at 75 Pa
data_groups_levels <- c('Set 1', 'Set 2', 'Set 3')
data_groups <- as.factor(rep(data_groups_levels, each=2))
moisture_level <- c(7, 3, 11, 10, 16, 6)
plotdt <- data.frame(data_groups, leakage_rates, moisture_level)
I use expression() to add exponents to the units in the legend. The following code generates the desired figure, but with the legend title text mis-formatted.
ggplot(plotdt, aes(data_groups)) +
geom_bar(aes(weight=moisture_level, fill=leakage_rates), position='dodge') +
labs(y='Moisture Level') +
labs(fill=expression(paste('Leakage Rate\nat 75 Pa\n(L/s-', m^2, ')', sep=''))) +
theme(panel.grid.major.x = element_blank(),
axis.title.x = element_blank())
The legend title appears left aligned except for the final line, which has a bunch of extraneous spaces in the middle of it.
Using legend_title_align=0 (suggested here) and/or legend_title=element_text(hjust=1) in theme() have no effect. Trying to add phantom() spacing also did not work (suggested here). The end of the top answer to this question notes the same problem I'm encountering but does not propose a solution.
Is there a way to get the meter squared term in the legend to be left-aligned like the rest of the text?
I am using ggplot 3.1.0 and R 3.5.1.
You can use the unicode representation of superscript two (U+00B2) and avoid the
problem-causing combination of expression() and a multi-line legend title:
ggplot(plotdt, aes(data_groups)) +
geom_bar(aes(weight=moisture_level, fill=leakage_rates), position='dodge') +
labs(y='Moisture Level') +
labs(fill=paste('Leakage Rate\nat 75 Pa\n(L/s-m\u00b2)', sep='')) +
theme(panel.grid.major.x = element_blank(),
axis.title.x = element_blank())
You can use atop to have lines "atop" each other.
Because you have 3 lines and atop only accepts 2 arguments however, you need to have 2 atop nested in one another. This makes the font on some of the lines smaller. The way to prevent this is to pass the expressions to either textstyle or displaystyle:
ggplot(plotdt, aes(data_groups)) +
geom_bar(aes(weight = moisture_level, fill = leakage_rates), position = "dodge") +
labs(y = "Moisture Level") +
labs(fill = expression(atop(atop(textstyle("Leakage Rate"),
textstyle("at 75 Pa")),
"(L/s-" ~m^2~ ")"))) +
theme(panel.grid.major.x = element_blank(), axis.title.x = element_blank())
I would just like to simply add an annotation to my ggplot with the exponential function on it like this graph:
excel graph
Here is the data:Data
Here is the code I used thus far:
dfplot<-ggplot(data, aes(dilution.factor,Concentation)) +
geom_point(size=3)+ geom_smooth(method="auto",se=FALSE, colour="black")+
scale_y_continuous(breaks=seq(0,14,by=2))
dfplot2<-dfplot+labs(x=('Dilution Factor'), y=expression('Concentration' ~
(ng/mu*L)))+
theme_bw() + theme(panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text = element_text(colour="black"),
axis.line = element_line(colour = "black"))
dfplot3<- dfplot2+annotate("text", x=3, y=10, label = "R^2 == 1",parse=TRUE)
dfplot3
dfplot4<-dfplot3+annotate("text", x=3, y=11, label =
as.character(expression("y=13.048e^-{0.697x}" ,parse=TRUE)))
dfplot4
I can get all the way up to putting the r^2 value (dfplot3)dfplot3
For some reason I cannot get it to add the exponential equation in. I keep getting this error:
Error: Aesthetics must be either length 1 or the same as the data (1): label
What am i doing wrong?
Not quite sure about the as.character(expression()) syntax you are using, but when you are parsing annotation text, ggplot2 doesn't understand the 'human' style notation shortcut of placing a number next to a letter 13.084e, you need to tell it explicitly this is multiplication. You also need == instead of =.
annotate("text", x=3, y=11, label = "y == 13.048*e^-{0.697*x}", parse =TRUE)
Edit: I see that you have included parse = TRUE inside the expression call, I think this is a mistake. To do it with expression you would write the following, but this is not in fact necessary:
annotate("text", x=3, y=11, label = as.character(expression("y == 13.048*e^-{0.697*x}")), parse = T)
Good morning,
I am making a heat map in ggplot of correlations between specific phenotypes. I would like to label each tile with the R^2 for the association.
I have a correlation matrix, max_all, which looks like this:
phenolist2 pheno1 pheno2 pheno3 pheno4 pheno5
max.pheno1 pheno1 0.05475998 0.05055959 0.05056578 0.10330301 0.05026997
max.pheno2 pheno2 0.15743312 0.05036100 0.05151750 0.04880302 0.31008809
max.pheno3 pheno3 0.05458550 0.07672537 0.04043422 0.16845294 0.14268895
max.pheno4 pheno4 0.05484327 0.04391523 0.05151107 0.09521869 0.19776296
max.pheno5 pheno5 0.08658449 0.05183693 0.16292683 0.22369817 0.53630569
Otherwise, my code is as follows:
tmp_Rsq <- melt(max_all)
tmp_Rsq <- ddply(tmp_Rsq, .(variable), transform, rescale=rescale(value))
labels_Rsq <- expression(paste(R^2, " = ", format(tmp_Rsq$value, digits=2), sep=""))
ggplot(tmp, aes(variable, phenolist2)) +
geom_tile(aes(fill =-log10(value)), colour = "white") +
geom_text(aes(label=as.character(labels_Rsq), parse = TRUE, size=4)) +
scale_fill_gradientn(colours = myPalette(101), name="-log10(P)", limits=c(0 , 3.5)) +
theme(axis.title.x = element_blank(), axis.title.y=element_blank(),
plot.title=element_text(size=20))+
theme(axis.text = element_text(colour="black", face="bold"))
My problem is that I can not get the expression to write out so that 2 is a superscript of R.
I realize there are a number of questions on this website addressing similar issues, for example ggplot2 two-line label with expression, Combining paste() and expression() functions in plot labels and Adding Regression Line Equation and R2 on graph but I have been unable to get the solutions suggested in these answers to apply to my case (likely because I have been trying to use a vector of labels).
Thanks a lot for your help.
Parse needs to be outside the aes, and the labels need to be a character vector.
labels_Rsq <- paste0("R^2 ==", format(tmp_Rsq$value, digits=2))
> head(labels_Rsq)
[1] "R^2 ==0.055" "R^2 ==0.157" "R^2 ==0.055" "R^2 ==0.055" "R^2 ==0.087" "R^2 ==0.051"
ggplot(tmp_Rsq, aes(variable, phenolist2)) +
geom_tile(aes(fill =-log10(value)), colour = "white") +
geom_text(aes(label=as.character(labels_Rsq)), parse = TRUE, size=4) +
# scale_fill_gradientn(colours = myPalette(101), name="-log10(P)", limits=c(0 , 3.5)) +
theme(axis.title.x = element_blank(), axis.title.y=element_blank(),
plot.title=element_text(size=20))+
theme(axis.text = element_text(colour="black", face="bold"))
How does one properly display special characters ("(", "ë", periods as commas, etc.) used in column names within a ggplot graphic?
My csv's column line looks like this:
r, á/b, ő/é, w/s (0.3), w/s (0.2), bins
And I'd like, for instance, the 4th variable to be displayed (in the ggplot legend), as "w/s (0.3)".
Here's my code:
require(reshape2)
library(ggplot2)
library(RColorBrewer)
fileName = paste("/2.csv", sep = "") # test file available here: https://www.dropbox.com/s/f2egxbuwwbba2q9/2.csv?dl=0
mydata = read.csv(fileName,sep=",", header=TRUE)
dataM = melt(mydata,c("bins"))
ggplot(data=dataM, aes(x= bins, y=value, colour=variable, size = variable)) +
geom_line(alpha = .9) +
scale_colour_manual(breaks=c("r","á/b","ő/é","w/s (0.3)","w/s (0.2)"), values=c("green","orange","blue","pink","yellow")) +
#scale_colour_brewer(type = "qual", palette = 7) +
scale_size_manual(breaks=c("r","á/b","ő/é","w/s (0.3)","w/s (0.2)"), values=c(1,0.5,0.5,0.5,0.5)) +
theme_bw() +
theme(plot.background = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(),
legend.key = element_blank(), legend.title = element_blank()) +
scale_y_continuous("D", expand=c(0,0)) +
scale_x_continuous("E", expand=c(0,0)) +
theme(legend.position="bottom")
Which produces this:
We can see how the legend wrongly display special characters. Any quick way (or not-so-quick way) to fix this?
(I have other questions about this graphics, but I believe it is preferred to ask a new complete question, which I'll do right now)
I think all you need to do is include check.names=FALSE in your read.csv() call; the special characters in your header are getting converted when the data is read in (see ?make.names for more information).
I was initially a little confused by your question because I assumed the problem was with accented characters such as ë, whereas in fact letters are not getting messed up -- it's only non-alphanumeric characters that are replaced by dots (also, strings starting with a numeric value would have "X" prepended).
This is probably extremely simple but I cannot seem to find the answer. I am adding greek lettering to my legend (mu). However, when I do this the black outline around my legend key boxes does not appear when I use legend.key = element_rect(colour = "black"). I also want the legend key text to be bold but this also doesn't work.
Anyone got any tips?
Here is an example:
Example data (sorry, not sure how to upload it so imported from .csv):
Name,Time,Dose,Variable,n,Mean,SD,Median,Upper.SEM,Lower.SEM
Ted,1,0,P,3,20.1341,1.049791,20,0.5728394,0.5569923
Fred,1,0,P,3,38.63702,1.042969,37.74,0.9499892,0.9271918
Ted,1,1,P,3,22.79528,1.110182,21.64,1.4179833,1.334943
Fred,1,1,P,3,24.25966,1.156925,23.82,2.1300073,1.9580866
Example code:
R<- subset(example, Dose=="0")
S<- subset(example, Dose=="1")
R_S<- rbind(R,S)
names(R_S)
w<- ggplot(R_S, aes(x=Name, y=Mean,fill=interaction(Name,Dose) ))
w<-w + geom_bar(stat="identity", position="dodge")
w<-w + geom_errorbar(aes(ymax=Mean+Upper.SEM, ymin=Mean-Lower.SEM), position=position_dodge(0.9), width=0.5)
w<- w+ scale_fill_manual(values=c("#00FF00","#FF0000","#98FB98","#FF7F50"),name="",labels=c(~"Fred- Control (0"* mu * M* ") ", ~"Ted- Control (0"* mu * M* ") ",~"Fred- Treated (1"* mu * M* ") ",~"Ted- Treated (1"* mu * M* ") "))
w + theme(legend.key = element_rect(colour = "black"))
w<-w+ theme(legend.position = "bottom")
w<-w+ theme(legend.key.size = unit(1.5, "lines"))
w<- w + theme(legend.text = element_text(colour="black", size = 18, face = "bold"))
w<-w+ theme(axis.title.x = element_text( face="bold",size=20))
w<-w+ theme(axis.title.y = element_text(face="bold",size=20))
w<-w+ theme(axis.text.x=element_text(face="bold",colour='black', size=18))
w<-w+ theme(axis.text.y=element_text(face="bold",colour='black', size=16))
w
This answer addresses the greek letter issue only.
As noted in ?plotmath:
Note that bold, italic and bolditalic do not apply to symbols, and hence not to the Greek symbols such as mu which are displayed in the symbol font.
and
In a UTF-8 locale any Unicode character can be entered, perhaps as a \uxxxx or \Uxxxxxxxx escape sequence, but the issue is whether the graphics device is able to display the character. The widest range of characters is likely to be available in the X11 device using cairo: see its help page for how installing additional fonts can help. This can often be used to display Greek letters in bold or italic.
So this works (depending on your device):
p <- ggplot(mtcars,aes(x = mpg,y = hp,color = factor(cyl))) + geom_point()
p + scale_color_manual(values = c('red','blue','green'),
labels = list(substitute(bold("\u03b2")),
substitute(bold("\u03b1")),
substitute(bold("\u03bc"))))