Label individual plots in facet_grid - r

I am trying to finish this graph, and what I need is to add the R-squared to each graph individually.
However, the labels are superimposed on each graph.
I used p + geom_text and p + geom_label without positive results.
Trajectories$date<-as.POSIXct(Trajectories$date,"%Y-%m-%d",tz = "UTC")
# Reorder names in a new variable
Trajectories$variable_f = factor(Trajectories$variable,
levels=c("canopy_cover", "Leaf_litter", "Chla", "Shrimps", "macroinvertebrates"))
levels(Trajectories$variable_f) <-
c("textstyle('Canopy openness')",
"textstyle('Leaf litter')",
"textstyle('Chlorophyll-')*italic('a')",
"textstyle('Shrimps')",
"atop(NA,atop(textstyle('Macroinvertebrate'),textstyle('density')))")
# Changes names in Facet_grid ---- es una manera buena, pero no la voy a usar --- Habria que labeller(variable_f = variable_f
#variable_f <- c("Canopy openness", "Leaf litter", "Chlorophyll-a","Shrimps","Macroinvertebrates")
#names(variable_f) <- c("canopy_cover", "Leaf_litter", "Chla", "Shrimps", "macroinvertebrates")
streams <- c("Prieta A", "Prieta B")
names(streams) <- c("QPA", "QPB")
# General graph -----------------------------------------------------------
p<- ggplot(Trajectories, aes(date,value)) +
geom_point(shape = 21, fill = "#bdd7e7", color = "#2171b5", size = 3) +
geom_smooth(se = T, size=1.7, color= "gray20", method = "gam", formula = y ~s(x)) +
geom_hline(yintercept = 0, color="gray20") +
xlab('Year') + ylab("Change in magnitude") +
theme(axis.title.x = element_text(size = 14, angle = 0)) + # axis x
theme(axis.title.y = element_text(size = 14, angle = 90)) + # axis 7
theme(axis.text.x=element_text(angle=0, size=10, vjust=0.5, color="black")) + #subaxis x
theme(axis.text.y=element_text(angle=0, size=10, vjust=0.5, color="black")) + #subaxis y
ylim(-3,3) +
theme(legend.position="none")+
theme(panel.grid.major = element_line(colour = "gray95"), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black")) +
theme(panel.border = element_rect(colour = "black", fill=NA, size=0.5)) +
facet_grid(vars(stream), vars(variable_f),
labeller = labeller(variable_f = label_parsed, stream = streams)) +
theme(
strip.text.x = element_text(size = 10, color = "black"),
strip.text.y = element_text(size = 10, color = "black"),
strip.placement = "outside") +
theme(strip.background=element_rect(color= "black", fill="gray85")) +
theme(strip.text.x = element_text(margin = margin(0.001,0,0.001,0, "cm"))) +
geom_vline(aes(xintercept=as.POSIXct("2017-09-21")), # Hurricane Maria
col= "red",linetype=4, alpha=0.9) +
geom_vline(aes(xintercept=as.POSIXct("2017-09-6")), # Hurricane Irma
col= "blue",linetype=4, alpha=0.9)
p
I tried to build a data frame with the labels. But it doesn't work, and it overlaps the labels.
labels <- data.frame(variable =c("canopy_cover","Leaf_litter","Chla","Shrimps","macroinvertebrates",
"canopy_cover","Leaf_litter","Chla","Shrimps","macroinvertebrates"),
label=c("R1","R2","R3","R4","R5","R6","R7","R8","R9","R10"),
stream= c("QPA","QPA","QPA","QPA","QPA",
"QPB","QPB","QPB","QPB","QPB"))
labels
p + geom_text(
size = 5,
data = labels,
mapping = aes(x = as.POSIXct("2017-09-6"), y = Inf, label = label),
hjust = 1.05,
vjust = 1.5
)
Thanks in advance

Related

Changing the order of the slices in a pie chart in R

I am trying to change the order of the slices in a pie chart in R. I want the largest value (38, which belongs to Agricultural intensification) on the right of 0 degrees, the second largest slice (20, belongs to Deforestation) on the left, the third largest value (17, Urbanization) as second one on the right, and the lowest value (10, Wetland or river modification) as second one on the left.
I used the code written out below. Thank you so much for helping me out!
Kind regards,
Stefanie
Pie chart
df <- data.frame(value = c(38, 20, 17, 10),
group = c('Agricultural intensification', 'Deforestation', 'Urbanization', 'Wetland or river modification'))
library(ggplot2)
ggplot(df, aes(x = "", y = value, fill = group)) +
labs(x='Taxon order', y='Driver', title='Driver per taxon order') + theme(plot.title = element_text(hjust = 0.5, size=20, face='bold')) +
geom_col(color = "black") +
coord_polar("y", start=0) +
geom_text(aes(label = paste0(slices, "%")), position = position_stack(vjust=0.5)) +
labs(x = NULL, y = NULL, fill = NULL) + theme(axis.line = element_line(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank()) +
theme_void() +
scale_fill_viridis_d()
Convert your group column to a factor and set the levels in your desired order:
df <- data.frame(
value = c(38, 20, 17, 10),
group = c("Agricultural intensification", "Deforestation", "Urbanization", "Wetland or river modification")
)
library(ggplot2)
df$group <- factor(df$group, levels = rev(c("Agricultural intensification", "Urbanization",
"Wetland or river modification", "Deforestation")))
ggplot(df, aes(x = "", y = value, fill = group)) +
labs(x = "Taxon order", y = "Driver", title = "Driver per taxon order") +
theme(plot.title = element_text(hjust = 0.5, size = 20, face = "bold")) +
geom_col(color = "black") +
coord_polar("y", start = 0) +
geom_text(aes(label = paste0(value, "%")), position = position_stack(vjust = 0.5)) +
labs(x = NULL, y = NULL, fill = NULL) +
theme(axis.line = element_line(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank()) +
theme_void() +
scale_fill_viridis_d()

r adding line (new coordinates) to ggplot2 scaterplot

How can I add a line with new x coordinates to my scatterplot? I get an error saying the line x-values must match those from my scatterplot.. I tried using geom_line() as you can see
library(ggplot2)
x <- c(1,2,3)
y <- c(4,5,6)
a <- seq(0.5,5, by = 0.5)
b <- seq(1,10)
ggplot(as.data.frame(cbind(x,y)), aes(x, y)) +
geom_point(shape = 1) +
geom_point(aes(2.5,2.5, colour = "My Portfolio"),
shape = 18,
size = 3) +
geom_line(aes(a, b)) +
ggtitle("Efficient Frontier") +
xlab("Volatility (Weekly)") +
ylab("Expected Returns (Weekly)") +
theme(plot.title = element_text(size=14, face="bold.italic", hjust = 0.5, margin=margin(0,0,15,0)),
axis.title.x = element_text(size = 10, margin=margin(15,0,0,0)),
axis.title.y = element_text(size = 10, margin=margin(0,15,0,0)),
panel.border = element_rect(colour = "black", fill=NA, size=1),
legend.position = c(0.93,0.06),
legend.title = element_blank(),
legend.text = element_text(size=8),
legend.background = element_rect(color = "black"),
legend.key=element_blank())
thanks!
You have to provide a new data.frame to geom_line() and set the aestetics accordingly.
library(ggplot2)
x <- c(1,2,3); y <- c(4,5,6)
a <- seq(0.5,5, by = 0.5); b <- seq(1,10)
ggplot(as.data.frame(cbind(x,y)), aes(x, y)) +
geom_point(shape = 1) +
geom_point(aes(2.5,2.5, colour = "My Portfolio"),
shape = 18,
size = 3) +
geom_line(data=data.frame(a,b), mapping=aes(x=a, y=b)) +
ggtitle("Efficient Frontier") +
xlab("Volatility (Weekly)") +
ylab("Expected Returns (Weekly)") +
theme(plot.title = element_text(size=14, face="bold.italic", hjust = 0.5, margin=margin(0,0,15,0)),
axis.title.x = element_text(size = 10, margin=margin(15,0,0,0)),
axis.title.y = element_text(size = 10, margin=margin(0,15,0,0)),
panel.border = element_rect(colour = "black", fill=NA, size=1),
legend.position = c(0.93,0.06),
legend.title = element_blank(),
legend.text = element_text(size=8),
legend.background = element_rect(color = "black"),
legend.key=element_blank())

R ggplot2: how to add legend if I use dataframe as data input?

I have tried any method online but the legend is not automatically showing up. Some previous issue says the usage of dataframe in ggplot2 is not preferable, but I have tried together() method and it doesn't work either. How to fix the bug?
Here is the data:
library(ggplot2)
library(gtable)
R = 0.01*c(7.000, 6.800, 6.620, 6.460, 6.330, 6.250, 6.200, 6.160, 6.125, 6.100)
Maturity = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
c = seq(from=0, to=0, length.out = length(R))
for (i in 1:length(R)){
for (j in 1:i){
c[i] = c[i] + 1/(1+R[j])^Maturity[j]
}
c[i] = (1-1/(1+R[i])^Maturity[i])/c[i]
}
Forward = seq(from=0, to=0, length.out = length(R))
for (i in 1:length(R)){
Forward[i] = (1+R[i+1])^2/(1+R[i])-1
}
Here is the plot code in RMarkDown:
```{R fig.width=2.7559, fig.height=2.0669291}
df = data.frame(Maturity=Maturity, ParYield=c, ForwardRate=Forward, R=R)
p = ggplot(data=df, aes(x=Maturity, y=ParYield)) +
ggtitle("Curve of Zero-coupon Yield, Par Yield, Forward Yield")+
labs(x = "Maturity (year)", y = "Par Yield") +
scale_y_continuous(breaks=seq(100*(min(na.omit(Forward), c)-0.01),
100*(max(na.omit(Forward),c)+0.01),by=0.1)/100,
sec.axis = dup_axis(),
labels = scales::number_format(accuracy = 0.005)) +
scale_x_continuous("Maturity", labels=as.character(Maturity), breaks=Maturity,
sec.axis = dup_axis()) +
theme_classic() +
geom_line(aes(y=ParYield), size=1) +
geom_line(aes(y=R), size=1) +
geom_line(aes(y=ForwardRate), size=1) +
geom_point(aes(y=ParYield), shape=21, fill=rgb(69/255, 117/255, 180/255),
size=3, stroke=1.5, color="black") +
geom_point(aes(y=R), shape=22, fill=rgb(145/255, 191/255, 219/255),
size=3, stroke=1.5, color="black") +
geom_point(aes(y=ForwardRate), shape=23, fill=rgb(224/255, 243/255, 248/255),
size=3, stroke=1.5, color="black") +
theme(plot.title = element_text(size=14, hjust=0.5),
text = element_text(size=15, colour = "black", family = "Calibri"),
axis.ticks.length = unit(-0.25, 'cm'),
axis.line = element_line(size=1),
axis.ticks = element_line(size=1),
axis.text.x = element_text(margin = margin(t=15)),
axis.text.x.top = element_text(margin = margin(b=15)),
axis.text.y.right = element_text(margin = margin(l=15, r=5)),
axis.text.y = element_text(margin = margin(l=5, r=15)),
axis.title.x.top = element_blank(),
axis.title.y.right = element_blank())+
guides(colour=guide_legend(override.aes = list(pch=c(16,21,20),fill=c('r','r','r'))))+
theme(legend.position = c(0.8,0.8), legend.justification = c("right", "top"))
p
Check this sketch and make the necessary adjustments as I am not clear on how colors must be set. Pay attention to the suggestion from #stefan and modify next code:
library(ggplot2)
#Code
df = data.frame(Maturity=Maturity, ParYield=c, ForwardRate=Forward, R=R)
ggplot(data=df, aes(x=Maturity, y=ParYield)) +
ggtitle("Curve of Zero-coupon Yield, Par Yield, Forward Yield")+
labs(x = "Maturity (year)", y = "Par Yield") +
scale_y_continuous(breaks=seq(100*(min(na.omit(Forward), c)-0.01),
100*(max(na.omit(Forward),c)+0.01),by=0.1)/100,
sec.axis = dup_axis(),
labels = scales::number_format(accuracy = 0.005)) +
scale_x_continuous("Maturity", labels=as.character(Maturity), breaks=Maturity,
sec.axis = dup_axis()) +
theme_classic() +
geom_line(aes(y=ParYield), size=1) +
geom_line(aes(y=R), size=1) +
geom_line(aes(y=ForwardRate), size=1) +
geom_point(aes(y=ParYield,colour='ParYield'), shape=21, fill=rgb(69/255, 117/255, 180/255),
size=3, stroke=1.5,show.legend = T) + #Black
geom_point(aes(y=R,colour='R'), shape=22,
fill=rgb(145/255, 191/255, 219/255),
size=3, stroke=1.5) + #Black
geom_point(aes(y=ForwardRate,colour='ForwardRate'), shape=23,
fill=rgb(224/255, 243/255, 248/255),
size=3, stroke=1.5) +
theme(plot.title = element_text(size=14, hjust=0.5),
text = element_text(size=15, colour = "black", family = "Calibri"),
axis.ticks.length = unit(-0.25, 'cm'),
axis.line = element_line(size=1),
axis.ticks = element_line(size=1),
axis.text.x = element_text(margin = margin(t=15)),
axis.text.x.top = element_text(margin = margin(b=15)),
axis.text.y.right = element_text(margin = margin(l=15, r=5)),
axis.text.y = element_text(margin = margin(l=5, r=15)),
axis.title.x.top = element_blank(),
axis.title.y.right = element_blank())+
guides(colour=guide_legend(override.aes = list(pch=c(16,21,20))))+
theme(legend.position = c(0.8,0.8), legend.justification = c("right", "top"))+
labs(color='Variable')
Output:
Other option would be:
#Code 2
df = data.frame(Maturity=Maturity, ParYield=c, ForwardRate=Forward, R=R)
ggplot(data=df, aes(x=Maturity, y=ParYield)) +
ggtitle("Curve of Zero-coupon Yield, Par Yield, Forward Yield")+
labs(x = "Maturity (year)", y = "Par Yield") +
scale_y_continuous(breaks=seq(100*(min(na.omit(Forward), c)-0.01),
100*(max(na.omit(Forward),c)+0.01),by=0.1)/100,
sec.axis = dup_axis(),
labels = scales::number_format(accuracy = 0.005)) +
scale_x_continuous("Maturity", labels=as.character(Maturity), breaks=Maturity,
sec.axis = dup_axis()) +
theme_classic() +
geom_line(aes(y=ParYield), size=1) +
geom_line(aes(y=R), size=1) +
geom_line(aes(y=ForwardRate), size=1) +
geom_point(aes(y=ParYield,colour='ParYield'), shape=21,
fill=rgb(69/255, 117/255, 180/255),
size=3, stroke=1.5,show.legend = T) +
geom_point(aes(y=R,colour='R'), shape=22,
fill=rgb(145/255, 191/255, 219/255),
size=3, stroke=1.5) +
geom_point(aes(y=ForwardRate,colour='ForwardRate'), shape=23,
fill=rgb(224/255, 243/255, 248/255),
size=3, stroke=1.5) +
scale_color_manual(values = c('black','black','black'))+
theme(plot.title = element_text(size=14, hjust=0.5),
text = element_text(size=15, colour = "black", family = "Calibri"),
axis.ticks.length = unit(-0.25, 'cm'),
axis.line = element_line(size=1),
axis.ticks = element_line(size=1),
axis.text.x = element_text(margin = margin(t=15)),
axis.text.x.top = element_text(margin = margin(b=15)),
axis.text.y.right = element_text(margin = margin(l=15, r=5)),
axis.text.y = element_text(margin = margin(l=5, r=15)),
axis.title.x.top = element_blank(),
axis.title.y.right = element_blank())+
guides(colour=guide_legend(override.aes = list(pch=c(16,21,20))))+
theme(legend.position = c(0.8,0.8), legend.justification = c("right", "top"))+
labs(color='Variable')
Output:
You need to map some additional aesthetics to variables in your data. I accomplished this by pivoting your data to a longer format.
library(tidyr)
df2 <- df %>% pivot_longer(-Maturity, names_to = "Yield", values_to = "Rate")
Then, I only used one geom_line and one geom_point, but with the new Yield variable mapped to group, fill, and shape. Now you can use scale_shape_manual and scale_fill_manual to set the appearances the way you want.
p = ggplot(data=df2, aes(x = Maturity, y = Rate, group = Yield,
fill = Yield, shape = Yield)) +
ggtitle("Curve of Zero-coupon Yield, Par Yield, Forward Yield")+
labs(x = "Maturity (year)", y = "Yield") +
scale_y_continuous(breaks=seq(100*(min(na.omit(Forward), c)-0.01),
100*(max(na.omit(Forward),c)+0.01),by=0.1)/100,
sec.axis = dup_axis(),
labels = scales::number_format(accuracy = 0.005)) +
scale_x_continuous("Maturity", labels=as.character(Maturity), breaks=Maturity,
sec.axis = dup_axis()) +
theme_classic() +
geom_line(size=1) +
geom_point(size=3, stroke=1.5, color="black") +
scale_shape_manual(values = c("ParYield" = 21, "R" = 22, "ForwardRate" = 23),
labels = c("Par Yield", "Zero-coupon Yield", "Forward Yield")) +
scale_fill_manual(values = c("ParYield" = rgb(69/255, 117/255, 180/255),
"R" = rgb(145/255, 191/255, 219/255),
"ForwardRate" = rgb(224/255, 243/255, 248/255)),
labels = c("Par Yield", "Zero-coupon Yield", "Forward Yield")) +
theme(plot.title = element_text(size=14, hjust=0.5),
text = element_text(size=15, colour = "black", family = "Calibri"),
axis.ticks.length = unit(-0.25, 'cm'),
axis.line = element_line(size=1),
axis.ticks = element_line(size=1),
axis.text.x = element_text(margin = margin(t=15)),
axis.text.x.top = element_text(margin = margin(b=15)),
axis.text.y.right = element_text(margin = margin(l=15, r=5)),
axis.text.y = element_text(margin = margin(l=5, r=15)),
axis.title.x.top = element_blank(),
axis.title.y.right = element_blank())+
guides(colour=guide_legend(override.aes = list(pch=c(16,21,20),fill=c('r','r','r'))))+
theme(legend.position = c(0.8,0.8), legend.justification = c("right", "top"))
I would recommend rethinking your y axis labels.'

Legend of the x axis in two Lines

[enter image description here][1]I write because I have a doubt, I need the legend of the graphic to stay in two lines to give more visibility to the graphic. I am trying to add the following code but it does not work
[# creamos el gráfico base
ggplot(UNICOS , aes(x = NOMBRE_SERVICIO, y = ID_GESTION_ATENCION)) +
geom_bar(stat="identity") +
theme(axis.text.x=element_text(angle=90,hjust=1)) +
stat_pareto(point.color = "blue",
point.size = 2,
line.color = "black",
bars.fill = "#66CCFF")+
ggtitle("Pareto tipo trámite")+
theme(plot.title = element_text(hjust = 0.5)) +
ylab("Cantidad") +
xlab("")+
scale_y_continuous(sec.axis = sec_axis(~./(max(.) * 0.95) * 100, name = "%Acumulado"))+
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "gray")) -> p
# Armamos las dos graficas
p1 <- p + scale_x_discrete(breaks = UNICOS$NOMBRE_SERVICIO\[1:10\]) + coord_cartesian(xlim = c(1, 10))
Add \n in the x variable names where you want the line breaks:
x.labels <- c("Notificación\naudiencia", "extraordinary long\nlong text", "text that cannot\nbe abbreviated\nby any means")
value <- c(10, 5, 3)
df <- data.frame(x.labels, value)
ggplot(df, aes(fill = 1, y = value, x = x.labels)) +
geom_bar(stat = "identity") +
theme(axis.text.x = element_text(angle = 90))

R stacked bar graph plotting geom_text

I'm trying to plot a stacked bar graph in R using ggplot. I also want to include percentage in each piece of bars for that piece. I tried to follow the posts 1, 2, 3 but the values are not exactly in their respective blocks. My data is a file in dropbox.
My code is as follows:
f<-read.table("Input.txt", sep="\t", header=TRUE)
ggplot(data=f, aes(x=Form, y=Percentage, fill=Position)) +
geom_bar(stat="identity", colour="black") +
geom_text(position="stack", aes(x=Form, y=Percentage, ymax=Percentage, label=Percentage, hjust=0.5)) +
facet_grid(Sample_name ~ Sample_type, scales="free", space="free") +
opts(title = "Input_profile",
axis.text.x = theme_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = theme_text(face="bold", size=11),
axis.title.x = theme_text(face="bold", size=9),
axis.title.y = theme_text(face="bold", size=9, angle=90),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank()) +
scale_fill_hue(c=45, l=80)
ggsave("Output.pdf")
The output is-
Any help is greatly appreciated.
Thank you for your help and time!
I think you're using an older version of ggplot2. Because with your code modified for ggplot2 v 0.9.3, I get this:
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(position = "stack", aes(x = Form, y = Percentage, ymax = Percentage, label = Percentage, hjust = 0.5))
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
You see that the text objects are normally placed properly. There are places where the bars are just too short so that the numbers overlap. You can also play with the size parameter.
To rectify that, you could do something like this to add up the numbers by yourself.
df <- ddply(df, .(Form, Sample_type, Sample_name), transform,
cum.perc = Reduce('+', list(Percentage/2,cumsum(c(0,head(Percentage,-1))))))
p <- ggplot(data = df, aes(x = Form, y = Percentage, fill = Position))
p <- p + geom_bar(stat = "identity", colour = "black")
p <- p + geom_text(aes(x = Form, y = cum.perc, ymax = cum.perc, label = Percentage, hjust = 0.5), size=2.7)
p <- p + facet_grid(Sample_name ~ Sample_type, scales="free", space="free")
p <- p + theme(plot.title = element_text("Input_profile"),
axis.text.x = element_text(angle = 90, hjust = 1, size = 8, colour = "grey50"),
plot.title = element_text(face="bold", size=11),
axis.title.x = element_text(face="bold", size=9),
axis.title.y = element_text(face="bold", size=9, angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
p <- p + scale_fill_hue(c=45, l=80)
p
This gives:
Here a solution using barchart from lattice.
library(latticeExtra)
barchart(Percentage~Form|Sample_type*Sample_name,data=dat,
groups =Position,stack=T,
panel=function(...){
panel.barchart(...)
ll <- list(...)
keep <- !is.na(ll$groups[ll$subscripts])
x <- as.numeric(ll$x[keep])
y <- as.numeric(ll$y[keep])
groups <- as.numeric(factor(ll$groups)[ll$subscripts[keep]])
for (i in unique(x)) {
ok <- x == i
ord <- sort.list(groups[ok])
pos <- y[ok][ord] > 0
nok <- sum(pos, na.rm = TRUE)
h <- y[ok][ord][pos]
panel.text(x = rep(i, nok),y = cumsum(h)-0.5*h,
label = h,cex=1.5)
}
},
auto.key = list(columns = 5),
par.settings = ggplot2like(n = 5),
lattice.options = ggplot2like.opts())

Resources