how to use facet_wrap to ggplot multiple location point in R? - r

I am trying to plot multiple location data using facet_wrap functionality of ggplot. I am having trouble in creating the legends (95% confidence interval is completely missed). Below is my code and I would appreciate any suggestion.
library(ggplot2)
library(lubridate)
set.seed(123)
DF1 <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "1 month"),
Ob = runif(60,1,5), L95 =runif(60, 0,4), U95 = runif(60,2,7), Sim = runif(60,1,5),
Loc = rep("Upstream", 60))
DF2 <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "1 month"),
Ob = runif(60,1,5), L95 =runif(60, 0,4), U95 = runif(60,2,7), Sim = runif(60,1,5),
Loc = rep("Downstream", 60))
DF <- dplyr::bind_rows(DF1,DF2)
DF$Loc <- factor(DF$Loc, levels = c("Upstream","Downstream"))
ggplot(DF, aes(x = Date))+
geom_ribbon(aes(ymin = L95, ymax = U95), fill = "grey30", alpha = 0.4)+
geom_line(aes(y = Ob, color = "blue"), size = 1 )+
geom_line(aes(y = Sim, color = "black"), size = 1, linetype = "dashed")+
geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
facet_wrap(~ Loc, ncol = 1, scales = "free_y")+
theme_bw()+
scale_color_identity(guide = "legend", breaks = c("grey30", "blue", "black"),
labels = c("95% confidence bound", "Observation","Simulation"))

Your fill is outside the aes function, so it cannot appear in the legend.
ggplot(DF, aes(x = Date))+
geom_ribbon(aes(ymin = L95, ymax = U95, color = "grey30"), fill = "grey30", alpha = 0.4)+
geom_line(aes(y = Ob, color = "blue"), size = 1 )+
geom_line(aes(y = Sim, color = "black"), size = 1, linetype = "dashed")+
geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
facet_wrap(~ Loc, ncol = 1, scales = "free_y")+
theme_bw()+
scale_color_identity(guide = "legend", breaks = c("grey30", "blue", "black"),
labels = c("95% confidence bound", "Observation","Simulation"))
ggplot(DF, aes(x = Date))+
geom_ribbon(aes(ymin = L95, ymax = U95, fill = "grey30"), alpha = 0.4)+
geom_line(aes(y = Ob, color = "blue"), size = 1 )+
geom_line(aes(y = Sim, color = "black"), size = 1, linetype = "dashed")+
geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
facet_wrap(~ Loc, ncol = 1, scales = "free_y")+
theme_bw()+
scale_color_identity(guide = "legend", breaks = c( "blue", "black"),
labels = c( "Observation","Simulation"),
name = 'Legend')+
scale_fill_identity(guide = "legend", labels = c("95% confidence bound"),
name=NULL)+
theme(legend.spacing.y = unit(-0.2, "cm"))+
theme(legend.title = element_text(margin=margin(b = 0.4, unit='cm')))

Here is how I would do this.
First, you are using fill for the ribbon, not color. Second, you need to actually map fill in aes, not just set it outside the aes. Then I would give the names you'd like in the aes calls, and use scale_*_manual to set the values you'd like:
ggplot(DF, aes(x = Date))+
geom_ribbon(aes(ymin = L95, ymax = U95, fill = "95% confidence bound"), alpha = 0.4)+
geom_line(aes(y = Ob, color = "Observation"), size = 1 )+
geom_line(aes(y = Sim, color = "Simulation"), size = 1, linetype = "dashed")+
geom_vline(xintercept = as.Date("2004-12-01"),color = "red", size = 1.30)+
facet_wrap(~ Loc, ncol = 1, scales = "free_y")+
theme_bw()+
scale_color_manual(values = c('blue', 'black'), name = NULL) +
scale_fill_manual(values = 'grey30', name = NULL)
There are a number of valid ways to approach this, but this is how many people do it.

Related

Define seperate aesthetics for geom_smooth when grouping data

I have some batch test data which was performed under different mixing conditions.
While I have managed to group the data, I am not sure how to define different aethitics for the geom_smooth lines.
M3<- ggplot(subset(VFA2, VFA %in% "HPr"), aes(x = Time, y = value, group = mix, shape = Test, colour = Test))+geom_point(size = 6, colour = "purple4")+
labs(x = "Anaerobic Time (h)\n Continuous Mixing", y = "HPr Concentration\n(mg HPr/L)")+theme(panel.background = element_rect(fill = "White", colour = "grey"),panel.grid.major = element_line(color = 'grey'), legend.position="bottom", text= element_text(size = 28, family = "Arial"))+
scale_x_discrete(breaks = factor(VFA2$Time), expand = c(-0.25,2))+scale_y_continuous(limits = c(-0.25, 60),breaks = c(0, 10,20, 30, 40, 50, 60))+[![enter image description here][1]][1] scale_shape_manual(values = c(0,1,2,5,7,13,14,9))
M3<- M3 + geom_smooth(method= "gam", formula = y~poly(x,4), se = F, colour = "black", linetype = "dashed")
Is this what you are looking for :
M3<- ggplot(subset(VFA2, VFA %in% "HPr"), aes(x = Time, y = value, group = mix, shape = Test))+
geom_point(size = 6, colour = "purple4")+
geom_smooth(aes(colour=mix), method= "gam", formula = y~poly(x,4), se = F, linetype = "dashed")+
labs(x = "Anaerobic Time (h)\n Continuous Mixing", y = "HPr Concentration\n(mg HPr/L)")+
theme(panel.background = element_rect(fill = "White", colour = "grey"),panel.grid.major = element_line(color = 'grey'), legend.position="bottom", text= element_text(size = 28, family = "Arial"))+
scale_x_discrete(breaks = factor(VFA2$Time), expand = c(-0.25,2))+
scale_y_continuous(limits = c(-0.25, 60),breaks = c(0, 10,20, 30, 40, 50, 60))+
scale_shape_manual(values = c(0,1,2,5,7,13,14,9))+
scale_color_manual(values = c("black", "red"))

ggplot how to plot pie charts on USA map with plot_usmap package or geom_polygon

I want to plot my data over US map and also add pie charts on the map. I used geom_polygon and also plot_usmap with geom_scatterpie but none of them worked. This my data https://iastate.box.com/s/rllzhkfmab475zr4ywur56cd31jhwl8g
f1<-ggplot() + geom_scatterpie(aes(x, y, group = region),
data = total, cols = "fuel",pie_scale = 1.3, long_format=TRUE) +
facet_grid(growth ~ emission)+
geom_text(aes(x, y, label = region),size = 4,family = "serif",
data = total, vjust = 1.2, nudge_y = -100000,check_overlap = TRUE)+
scale_fill_manual(legend_title,values=mypal[names(mypal) %in% total[,2]])+
theme(legend.title = element_text(family="sans",face = "bold", size = 12), legend.text = element_text(family="sans",size = 11),legend.position = "bottom")+
theme(strip.text = element_text(family="sans",size = 14))+
theme(panel.background = element_rect(fill = NA, color = "gray"))
f1+ggplot(states_data, aes(x, y, fill = value, group = group)) +
geom_polygon()+
scale_fill_continuous(low = "white", high = "red", name = "Ele gen (EJ)", label =
scales::comma) +
facet_grid(growth ~ emission) +
coord_equal() +
ggthemes::theme_map() +
theme(legend.position = "bottom")
and also this
plot_usmap(data=states_data,values = "value", regions = "states", exclude = c("AK", "HI"))
+scale_fill_continuous(low = "white", high = "red", name = "Ele gen (EJ)", label =
scales::comma)+
geom_scatterpie(aes(x, y, group = region),
data = total, cols = "fuel",pie_scale = 1.3, long_format=TRUE) +
facet_grid(growth ~ emission)+
geom_text(aes(x, y, label = region),size = 4,family = "serif",
data = total, vjust = 1.2, nudge_y = -100000,check_overlap = TRUE)+
scale_fill_manual(legend_title,values=mypal[names(mypal) %in% total[,2]])+
theme(legend.title = element_text(family="sans",face = "bold", size = 12),
legend.text = element_text(family="sans",size = 11),legend.position = "bottom")+
theme(strip.text = element_text(family="sans",size = 14))+
theme(panel.background = element_rect(fill = NA, color = "gray"))
I want to plot this two together:

Missing Dots and Line Style in Figure Legend with ggplot2

After running the following commands:
Population <- c("A", "A", "A", "A", "B", "B", "B", "B")
Group <- rep(c("Experimental", "Experimental", "Control", "Control"), 2)
wave <- rep(c("Pretest", "Posttest"), 4)
outcome <- c(-.3, -.2, -.3, .4, -.6, -.5, -.6, .6)
ci <- rep(c(.13, .14), 4)
df <- data.frame(Population, Group, wave, outcome, ci)
df$wave <- factor(df$wave,levels = c('Pretest','Posttest'))
library(ggplot2)
pd <- position_dodge(0.1)
ggplot(df, aes(x = wave, y = outcome, color = interaction(Population, Group), shape = Group, group = interaction(Population, Group))) +
geom_errorbar(aes(ymin = outcome - ci, ymax = outcome + ci), width = .25, position = pd, size=.5) +
geom_line(aes(linetype = Group), position = pd, size=1, show.legend = FALSE) +
geom_point(position = pd, size = 3.5, fill = "white", stroke = 1.25, show.legend = FALSE) +
scale_color_manual(values = c("#000000", "#606060", "#000000", "#606060")) +
scale_shape_manual(values = c(23, 21)) +
coord_cartesian(xlim = c(1.4, 1.6), ylim = c(-.91, .91)) +
labs(title = "Outcomes by Population and Study Group", x = "Time", y = "Outcome\nLower scores denote fewer instances", color = "Population and Study Group") +
theme(plot.title = element_text(hjust = 0.5), axis.text.x = element_text(color = "black"), axis.text.y = element_text(color = "black"), panel.background = element_rect(fill = "#F0F0F0"))
I generate a figure that does not have dots symbols or correct line styles in the legend:
How can I:
add the dots shown in the figure itself into the legend and
have the legend lines reflect that some of dotted lines in the figure?
TYIA.
The simplest way is to create another variable that would reflect the interaction instead of creating it on the fly. If we build the plot step by step, this below gives the dots and errorbars:
library(ggplot2)
pd <- position_dodge(0.1)
df$grp = paste(df$Population,df$Group,sep=".")
g = ggplot(df, aes(x = wave, y = outcome, color = grp, shape = grp))+
geom_errorbar(aes(ymin = outcome - ci, ymax = outcome + ci), width = .25, position = pd, size=.5) +
geom_point(position = pd, size = 3.5, fill = "white", stroke = 1.25) +
scale_color_manual(values = c("#000000", "#000000","#606060", "#606060")) +
scale_shape_manual(values = c(23,21,23,21)) +
coord_cartesian(xlim = c(1.4, 1.6), ylim = c(-.91, .91)) +
labs(title = "Outcomes by Population and Study Group", x = "Time", y = "Outcome\nLower scores denote fewer instances") +
theme(plot.title = element_text(hjust = 0.5), axis.text.x = element_text(color = "black"),
axis.text.y = element_text(color = "black"), panel.background = element_rect(fill = "#F0F0F0"))
print(g)
Then add the line while specifying the legend:
g +
geom_line(inherit.aes=FALSE,aes(x = wave, y = outcome,group=grp,linetype=grp)) +
scale_linetype_manual(values=c("solid","dashed","solid","dashed"))

Trying to add legend using geom_abline

I have a data frame, saved as df, with two columns of points that I would like to plot. In addition, I would like to plot two lines on the plot and would like to have a legend for these lines. Here is my code:
ggplot(df, aes(x = x, y = y)) +
geom_point(color = "black", shape = 16, alpha = 1) +
scale_x_continuous(name = "x", limits = c(-5, 5)) +
scale_y_continuous(name = "y", limits = c(-5, 5)) +
geom_abline(intercept = 0, slope = 4/3, linetype = "dashed",
color = "gray40", size = 1, aes(colour = "XNULL")) +
geom_abline(intercept = 0, slope = 0, linetype = "dotted",
color = "gray40", size = 1, aes(colour = "YNULL")) +
scale_color_manual(name = "", values = c("XNULL" = "red", "YNULL" = "blue")) +
theme(panel.background = element_rect(fill = "white"),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
legend.position = "bottom")
However, when I run this, no legend comes up (I would like to have the legend on the bottom). Any suggestions as to what I am doing wrong? I am new at using ggplot2, and none of the solutions I looked up on other forums helped.
You can try creating another data.frame to contain information about your ablines:
df = data.frame(x=runif(10),y=runif(10))
df2 = data.frame(intercept=0,slope=c(4/3,0),type=c("XNULL","YNULL"))
Then we can call geom_abline specifying the aes so that we can use
ggplot(df, aes(x = x, y = y)) +
geom_point(color = "black", shape = 16, alpha = 1) +
scale_x_continuous(name = "x", limits = c(-5, 5)) +
scale_y_continuous(name = "y", limits = c(-5, 5)) +
geom_abline(data=df2,aes(intercept=intercept,slope=slope,
linetype=type,col=type),size = 1) +
scale_color_manual(name = "", values = c("XNULL" = "red", "YNULL" = "blue")) +
scale_linetype_manual(name = "", values = c("XNULL" = "dashed", "YNULL" = "dotted")) +
theme(panel.background = element_rect(fill = "white"),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
legend.position = "bottom")
From the documentation:
These geoms act slightly differently from other geoms. You can supply
the parameters in two ways: either as arguments to the layer function,
or via aesthetics. If you use arguments, e.g. geom_abline(intercept =
0, slope = 1), then behind the scenes the geom makes a new data frame
containing just the data you've supplied.
Apparently, you have to specify intercept and slope in aes, so that it works.
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
coord_cartesian(xlim = c(0,10), ylim = c(0,10)) +
geom_abline(aes(intercept = 0, slope = 0, color = "X"), linetype = "dotted") +
geom_abline(aes(intercept = 0, slope = 4/3, color = "Y"),linetype = "dashed") +
scale_color_manual(values = c(X = 'grey', Y = 'black'))
Created on 2020-02-12 by the reprex package (v0.3.0)

GGPLOT - Order of Multiple legends (geom_line and geom_line plus geom_point)

I searched for many questions already answered, but none of them can help me.
This is my code:
ggplot(z, aes(x=`Fecha de muestreo`, y = Valor, color = `Nombre de la estaciĆ³n`)) +
geom_line(size = 0.4) +
geom_point(size=0.5) +
scale_x_date(date_labels = "%b", breaks = "1 month", limits = c(as.Date("2019-1-1"), as.Date("2019-12-20"))) +
scale_y_continuous("pH (unidades de pH)", limits = c(3, 11), breaks = c(3:11)) +
geom_hline(aes(yintercept = 6.5, linetype = "ECA cat.3 inf D1 y D2 : 6.5"), colour = "Blue", size = 0.4)+
geom_hline(aes(yintercept = 8.4, linetype = "ECA cat.3 sup. D1 : 8.4"), colour = "Green", size = 0.4)+
geom_hline(aes(yintercept = 8.5, linetype = "ECA cat.3 sup. D2 : 8.5"), colour = "red", size = 0.4)+
scale_linetype_manual(name = NULL, values = c(1, 1, 1), # values = tipo de lineas
guide = guide_legend(override.aes = list(color = c("blue", "Green", "Red")))) +
theme(axis.text=element_text(size=6),
legend.margin = unit(-0.2, "cm"),
axis.title=element_text(size=7,face="bold")) +
theme(legend.text=element_text(size=6),
legend.title = element_blank(),
legend.spacing.x = unit(.2, 'cm')) +
theme(legend.key = element_rect(fill = "white")) +
theme(panel.background = element_rect(fill = "white")) +
theme(panel.grid = element_line(colour= "gray"))
This is the graph:
I need to change the order of the legends: the "ECAS" should be at the bottom.
How can I do it?
This should be possible using the order term of guides(). For example:
library(ggplot2)
a <- ggplot(mtcars, aes(wt, mpg,
color = as.character(cyl),
fill = as.character(gear))) +
geom_point(size = 5, shape = 21, stroke = 2) +
scale_color_discrete(name = "cyl as color") +
scale_fill_discrete(name = "gear as fill")
a
To reverse the order, we can add: (note, ordering seems to be from the bottom up)
a +
guides(color = guide_legend(order = 0),
fill = guide_legend(order = 1))

Resources