Specific Barplot in R ggplot - r

Hello I will try for a last time,
I am doing my best to draw a barplot like the following Figure:
However it seems impossible with R.
Any idea?
Thanks in advance,
Peter
Attached the code I used.
groupe2<-rep(c(rep("P",4),rep("I",4)),2)
groupe<-rep(c("PPP","PPI","PIP","PII","IPP","IPI","IIP","III"),2)
OR_A<-c(1.00,0.86,0.88,0.90,0.77,0.68,0.77,0.70)
ICinf_A<-c(NA,0.70,0.72,0.76,0.60,0.50,0.61,0.61)
ICsup_A<-c(NA,1.06,1.07,1.06,1.00,0.92,0.96,0.81)
OR_B<-c(1.00,0.97,1.01,0.81,0.73,0.69,0.61,0.58)
ICinf_B<-c(NA,0.78,0.77,0.62,0.61,0.57,0.50,0.52)
ICsup_B<-c(NA,1.20,1.28,1.05,0.81,0.82,0.71,0.65)
OR_C<-c(1.00,1.03,0.86,0.65,0.68,0.58,0.47,0.37)
ICinf_C<-c(NA,0.84,0.67,0.50,0.59,0.49,0.40,0.33)
ICsup_C<-c(NA,1.27,1.10,0.86,0.78,0.69,0.56,0.41)
Cohort<-c(rep(" PC",8), rep("RIC",8))#, rep("RIC",8))
OR<-c(OR_A,OR_B)#,OR_C)
ICinf<-c(ICinf_A,ICinf_B)#,ICinf_C)
ICsup<-c(ICsup_A,ICsup_B)#,ICsup_C)
rm(dataOR)
dataOR<-data.frame(OR,groupe,Cohort,groupe2,ICinf,ICsup)
names(dataOR)
dataOR[, "groupe"] <- factor(dataOR[, "groupe"] ,
levels = c("PPP","PPI","PIP","PII","IPP","IPI","IIP","III"))
##########
library(ggdag)
ggplot(dataOR, aes(fill=outcome, y=OR, x=groupe)) +
geom_bar(position="dodge", stat="identity", color = "gray95", size = 0.25) +
# scale_fill_brewer(palette="Blues")+
scale_fill_manual(values = RColorBrewer::brewer.pal(5, "Blues")[3:5]) +
geom_errorbar(aes(ymin=ICinf, ymax=ICsup), width=.4, position=position_dodge(.9))+
geom_hline(yintercept=1) +
geom_point(position = position_dodge(0.9), size = 0.5, show.legend = F) +
scale_y_continuous(expand = expand_scale(mult = c(0, 0.05))) +
facet_wrap(~groupe, nrow = 1, scales = "free_x") +
labs(fill = NULL) +
theme(legend.position = "top",
legend.key.height = unit(0.2, "cm"),
legend.background = element_rect(color = "black", size = 0.4),
axis.line = element_line(color = "black"),
axis.text.x = element_blank(),
axis.ticks = element_blank(),
panel.grid.major.x = element_blank(),
axis.title = element_text(face = "bold"))

Related

Can you shift the position of a facet label or strip bar in ggplot?

I'm using ggplot to graph a forest plot. I have used facet labels to label groups (in example below Test1, Test2, Test3). Is there a way to slightly shift the actual position of the facet label/strip to the left (as indicated by the arrows in my picture below)?
I can shift the position of the text within the facet label but I think I have done that as much as possible. Thus, I think I need to shift the actual facet label (strip bar/rectangle) itself. Is this possible?
Would be very grateful if anyone could help me or point out a way to get a similar effect!
Please find reproducible code here:
library(dplyr)
library(ggplot2)
library(ggforce)
library(tidyverse)
# Reproducible dataset
df <- data.frame(outcome = c('outcome1', 'outcome1', 'outcome2','outcome2','outcome3','outcome3','outcome4','outcome4','outcome5','outcome5'),
type = c('Test1','Test1','Test2','Test2', 'Test3', 'Test3', 'Test3','Test3', 'Test3', 'Test3'),
Coef = c(0.10026935, 0.10026935, 0.13713358, 0.13713358,0.07753188,0.07753188,0.09193794,0.09193794,0.06170916,0.06170916),
CIr_low = c(0.070955475,0.070955475,0.108705781,0.108705781,0.052595474,0.052595474,0.056340327,0.056340327,0.036185918,0.036185918),
CIr_high = c(0.12958323,0.12958323,0.16556139,0.16556139,0.10246828,0.10246828,0.12753555,0.12753555,0.08723240,0.08723240),
model = c(1,2,1,2,1,2,1,2,1,2))
# Set type as factor
df <- df %>% mutate(type = fct_relevel(type, "Test1","Test2","Test3"))
# Plot with ggplot
ggplot(df, aes(x = outcome, y = Coef, ymin = CIr_low,ymax =CIr_high,fill = as.factor(type))) +
geom_errorbar(aes(x= outcome, ymin=CIr_low, ymax=CIr_high), width=0.2,cex=0.5)+
geom_point(shape = 18, size = 5)+
facet_grid(type ~ ., scales = "free", space = "free") +
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(limits = c(-0.1, 0.25)) +
ggforce::facet_col(facets = type ~ ., scales = "free_y", space = "free", strip.position = "top")+
theme_bw()+
coord_flip() +
xlab('Group')+
ylab(expression("Standardized" ~ beta *" (95%CI)"))+
theme(line = element_line(colour = "black", size = 0.5),
plot.margin = margin(0.5, 0.5, 0.5, 0.5, unit = "cm"),
strip.background = element_rect(colour = "white", fill="white"),
strip.text = element_text(colour = "black",face="italic"),
strip.text.x = element_text(size = 12,angle = 0,hjust = 0,face="bold.italic", color="darkblue"),
legend.position ="none",
axis.line.x = element_line(colour = "black"),
axis.line.y = element_blank(),
panel.border= element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.spacing = unit(2, "lines"),
axis.ticks = element_blank(),
axis.title.x = element_text(colour = "black"),
axis.title.y = element_blank(),
axis.text=element_text( color = "black")
)
You can try:
ggplot(df, aes(x = outcome, y = Coef, ymin = CIr_low,ymax =CIr_high,fill = as.factor(type))) +
geom_errorbar(aes(x= outcome, ymin=CIr_low, ymax=CIr_high), width=0.2,cex=0.5)+
geom_point(shape = 18, size = 5, show.legend = F)+
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(expression("Standardized" ~ beta *" (95%CI)"),limits = c(-0.1, 0.25)) +
xlab("")+
coord_flip() +
facet_grid(type~., scales = "free", space = "free_y", switch = "y") +
theme_minimal() +
theme(strip.placement = "outside",
strip.text.y.left = element_text(angle = 0,vjust = 1,size=12))
Or use a cowplot approach with ggtitle
plots <- df %>%
split(.$type) %>%
map2(.,names(.), ~ggplot(.x, aes(x = outcome, y = Coef, ymin = CIr_low,ymax =CIr_high,fill = as.factor(type))) +
geom_errorbar(aes(x= outcome, ymin=CIr_low, ymax=CIr_high), width=0.2, size=0.5)+
geom_point(shape = 18, size = 5, show.legend = F)+
geom_hline(yintercept = 0, linetype = 'dashed', col = 'black') +
scale_y_continuous(limits = c(-0.1, 0.25))+
coord_flip() +
xlab('')+
ylab(expression("Standardized" ~ beta *" (95%CI)"))+
ggtitle(.y)+
theme_minimal(base_size = 12)+
theme( panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.title.position = "plot"))
cowplot::plot_grid(plots$Test1 + theme(axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank()),
plots$Test2 + theme(axis.title.x = element_blank(), axis.ticks.x = element_blank(), axis.text.x = element_blank()),
plots$Test3, ncol = 1)

How do I change a dodged bar graph so the bars follow a selected color pattern,not a gradient, and how to keep bars from changing positions?

csv file I'm working with
***I'm relatively new to R and coding in general. I have done a bit of Googling and trial and error to figure out my mistakes/solve my issues but to no avail. Help is greatly appreciated.
For the file above, I'm creating a dodged bar graph to show each quarter from 2017-2020. However, it produces a gradient and I want individual colors. For example, I want all Q1s to be red. All Q2s to be green, etc. I tried using scale_fill_manual() but had no luck.
gradient result
testplot1<-ggplot(test, aes(x=Year, y=Sales, fill=Sales))+
geom_bar(position = "dodge", stat="identity", aes(group=Q))+
labs(x = "Year", y = "Sales",
title="Sales Year-Over-Year",
subtitles = "Test")+
theme_bw()+
theme_minimal()+
theme(axis.ticks = element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.major.x=element_blank(),
plot.title= element_text(face="bold", size=14, color = "black", hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))+
theme(legend.position = "none")+
geom_text(aes(label=dollar(Sales)), hjust = 0.5, vjust = -0.8, color = "black",
size = 2,position = position_dodge2(width = 1),inherit.aes = TRUE)+
scale_y_continuous(labels=dollar_format(prefix="$"), expand = c(0,0), limits = c(-200000,800000))
testplot1
I tried setting the fill to as.factor(Sales), but then it changes the order of the 2020 quarters. Any help is appreciated.
various colors and rearranged 2020 quarters
testplot<-ggplot(test, aes(x=Year, y=Sales, fill=as.factor(Sales)))+
geom_bar(position = "dodge", stat="identity", aes(group=Q))+
labs(x = "Year", y = "Sales",
title="Sales Year-Over-Year",
subtitles = "Test")+
theme_bw()+
theme_minimal()+
theme(axis.ticks = element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.major.x=element_blank(),
plot.title= element_text(face="bold", size=14, color = "black", hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))+
theme(legend.position = "none")+
geom_text(aes(label=dollar(Sales)), hjust = 0.5, vjust = -0.8, color = "black",
size = 2,position = position_dodge2(width = 1),inherit.aes = TRUE)+
scale_y_continuous(labels=dollar_format(prefix="$"), expand = c(0,0), limits = c(-200000,800000))
testplot
It can be tricky when you're trying to color a variable that you know is a categorical variable (the quarter) but that is listed as a number and thus that R interprets as a continuous variable. You can get around that by coding it as a factor like this:
ggplot(test, aes(x=Year, y=Sales, fill=as.factor(Q)))+
geom_bar(position = "dodge", stat="identity") +
labs(x = "Year", y = "Sales",
title="Sales Year-Over-Year",
subtitles = "Test") +
scale_fill_manual(values = c("red", "green", "blue", "gray")) +
theme_bw() +
theme_minimal() +
theme(axis.ticks = element_blank(),
panel.grid.minor.x=element_blank(),
panel.grid.major.x=element_blank(),
plot.title= element_text(face="bold", size=14, color = "black", hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(colour = "black"))+
theme(legend.position = "none")+
geom_text(aes(label=dollar(Sales)), hjust = 0.5, vjust = -0.8, color = "black",
size = 2, position = position_dodge2(width = 1),
inherit.aes = TRUE) +
scale_y_continuous(labels=dollar_format(prefix="$"),
expand = c(0,0), limits = c(-200000,800000))
The critical bit is the fill = as.factor(Q).

How to change certain aesthetics of facet_grid ggplot?

I created this plot using facet_grid and patchwork because I needed to have a customized secondary y-axis for each of the parameter and they all have different scale. I have successfully tweaked most of the aesthetics to match with what I need for the graph except for a couple of places:
Matching color with "site." I would like to match red, blue, and green to Port, Bluff, and Palm respectively. It didn't work with the code I have in scale_color_manual.
Renaming the strip text. I tried using expression(paste()) before but it wasn't working, especially with greek letter. I would like to have these respective stip text on the right for each row: ETR[max], ɑ, and E[k].
Letter in the [] are subscripts.
Thank you for any pointers. I ran out of things to try to make this week, especially with the strip texts.
My dataframe: data file
My codes are:
abrv_mo <- with (params, month.abb[month]) params <- transform(params, month = abrv_mo) params <- params[order(match(params$month, month.abb)), ] params$month <- factor(params$month, month.abb, ordered = TRUE) params$month<- as.Date(ISOdate(2019, as.numeric(params$month), 15))
p1 <- ggplot() + geom_hline(yintercept = 19.6, linetype = "dashed")
+ geom_line(data = tmpr2,
aes(month, tmp*0.98),
alpha = 0.4) + geom_errorbar(data = subset(params, variable == "max"),
aes(x= month, ymin = mean - se, ymax = mean +se, color = site),
width = 8) + geom_point(data = subset(params, variable == "max"),
aes(x=month, y=mean, color = site, group=site),
size = 2.5) + facet_grid(rows = vars(variable),
cols = vars(site),
switch = "y", scale = "free_y") + scale_x_date(name = NULL, date_labels = "%b",
seq(as.Date("2019-01-15"),
as.Date("2019-07-15"), by = "1 month")) + # ?strftime() for more options scale_y_continuous(limits = c(5,40), breaks = seq(5, 40, by = 15),
expand = c(0,0),
sec.axis = sec_axis(~./0.98)) + scale_color_manual(name = "Site",
labels = c("Port", "Bluff", "Palm"),
values = c("#FC4E07","#00AFBB", "#C3D7A4")) + theme_bw() + theme(plot.background = element_blank(),
strip.background = element_blank(),
strip.placement = "outside",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_rect(size=1, colour = "black"),
panel.spacing = unit(0.3, "lines"),
axis.line = element_line(size=0.1, colour = "black"),
axis.ticks.y = element_line(size=0.5, colour = "black"),
axis.text.x = element_blank(),
axis.text.y = element_text(size=10, color="black", margin = margin(t = 0.5, l = 0.5)),
text = element_text(size = 18),
legend.position="none",
plot.margin=margin(l = -1, unit = "cm")) + ylab(NULL)
p2 <- ggplot() + geom_hline(yintercept = 0.16, linetype = "dashed")
+ geom_line(data = tmpr2,
aes(month, tmp*0.008),
alpha = 0.4) + geom_errorbar(data = subset(params, variable=="slope"),
aes(x= month, ymin = mean - se, ymax = mean +se, color = site),
width = 8) + geom_point(data = subset(params, variable == "slope"),
aes(x=month, y=mean, color=site, group=site),
size = 2.5) + facet_grid(rows = vars(variable),
cols = vars(site),
switch = "y",
scale = "free_y") + scale_x_date(name = NULL, date_labels = "%b",
seq(as.Date("2019-01-15"),
as.Date("2019-07-15"), by = "1 month")) + # ?strftime() for more options scale_y_continuous(breaks = seq(0.15,
0.26, by = 0.05),
expand = c(0,0),
limits = c(0.15,0.26),
sec.axis = sec_axis(~./0.008, name = "Temperature (°C)")) + scale_color_manual(name = "Site",
labels = c("Port", "Bluff", "Palm"),
values = c("#FC4E07","#00AFBB", "#C3D7A4")) + theme_bw() + theme(plot.background = element_blank(),
strip.background = element_blank(),
strip.placement = "outside",
strip.text.x = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_rect(size=1, colour = "black"),
panel.spacing = unit(0.3, "lines"),
axis.line = element_line(size=0.1, colour = "black"),
axis.ticks.y = element_line(size=0.5, colour = "black"),
axis.text.x = element_blank(),
axis.text.y = element_text(size=10, color="black", margin = margin(t = 0.5, l = 0.5)),
axis.text.y.right = element_text(size=10, color="black", margin = margin(t = 0.5, r = 10)),
text = element_text(size = 18),
legend.position="none",
plot.margin=margin(l = -1.5, unit = "cm")) + ylab(NULL)
p3 <- ggplot() + geom_hline(yintercept = 140, linetype = "dashed") + geom_line(data = tmpr2,
aes(month, tmp*7),
alpha = 0.4) + geom_errorbar(data = subset(params, variable=="ek"),
aes(x= month, ymin = mean - se, ymax = mean +se, color = site),
width = 8) + geom_point(data = subset(params, variable=="ek"),
aes(x=month, y=mean, color=site, group=site),
size = 2.5) + facet_grid(rows = vars(variable),
cols = vars(site),
switch = "y",
scale = "free_y") + scale_x_date(name = NULL, date_labels = "%b",
seq(as.Date("2019-01-15"),
as.Date("2019-07-15"), by = "1 month")) + # ?strftime() for more options scale_y_continuous(expand = c(0,0),
breaks = seq(25, 250, by = 100),
limits = c(25,250),
sec.axis = sec_axis(~./7)) + scale_color_manual(name = "Site",
labels = c("Port", "Bluff", "Palm"),
values = c("#FC4E07","#00AFBB", "#C3D7A4")) + theme_bw() + theme(plot.background = element_blank(),
strip.background = element_blank(),
strip.placement = "outside",
strip.text.x = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_rect(size=1, colour = "black"),
panel.spacing = unit(0.3, "lines"),
axis.line = element_line(size=0.1, colour = "black"),
axis.ticks.y = element_line(size=0.5, colour = "black"),
axis.text.x = element_text(angle = 45,size=10, color="black", hjust = 1,
margin = margin(t = 0.5, r = 0.5)),
axis.text.y = element_text(size=10, color="black", margin = margin(t = 0.5, l = 0.5)),
text = element_text(size = 18),
legend.position="none",
plot.margin=margin(l = -1.5, unit = "cm")) + ylab(NULL)
library(patchwork)
p1 + p2 + p3 + plot_layout(ncol = 1)

Trouble getting stat_ecdf legend line color to match plot color, and removal of horizontal lines

I have a plot with three ECDFs and three vertical lines, and cannot get the stat_ecdf legend line color to match the actual line color.
Here is the code for just the ECDF plot:
set.seed(124)
allDTI <- data.frame(values=rnorm(1000,500,200),type=sample(LETTERS[1:3],1000,T))
meanALLDTI <- ddply(allDTI, "type", summarise, values.mean=mean(values, na.rm=TRUE), n)
ggplot(allDTI, aes(x=values, color=type)) +
stat_ecdf(size=1, show_guide=T) +
xlab(expression('Index Value')) +
ylab("Cumulative Density") +
ggtitle(expression(TI[d]~'and'~TI[l]~'and'~TI[w])) +
scale_x_continuous(expand = c(0,0)) +
scale_y_continuous(expand = c(0,0)) +
theme(text = element_text(size=20),
plot.title = element_text(size=30,face="bold",vjust=1),
axis.title.x=element_text(size=20,face="bold",vjust=0,hjust=0.5),
axis.title.y=element_text(size=20,face="bold",vjust=1.0,hjust=0.5),
legend.position = c(0.85, 0.25),
legend.text.align = 0,
legend.box = 'horizontal',
legend.margin = unit(45.0, 'line'),
legend.text=element_text(size=28,vjust=0,hjust=0),
legend.key.height = unit(1.5, 'line'),
legend.key.width = unit(1.5, 'line'),
panel.background = element_rect(fill = "white")) +
scale_color_manual(values=c('grey10','grey30','grey50'),
labels=c(expression(TI[d]),expression(TI[l]),
expression(TI[w]))) +
guides(color = guide_legend(title=NULL))
Here is the plot:
But I can't figure out how to add the vertical lines I want to add in the manner I want to add them:
Code:
ggplot(allDTI, aes(x=values, color=type)) +
stat_ecdf(size=1, show_guide=T) +
xlab(expression('Index Value')) +
ylab("Cumulative Density") +
ggtitle(expression(TI[d]~'and'~TI[l]~'and'~TI[w])) +
scale_x_continuous(expand = c(0,0)) +
scale_y_continuous(expand = c(0,0)) +
theme(text = element_text(size=20),
plot.title = element_text(size=30,face="bold",vjust=1),
axis.title.x=element_text(size=20,face="bold",vjust=0,hjust=0.5),
axis.title.y=element_text(size=20,face="bold",vjust=1.0,hjust=0.5),
legend.position = c(0.85, 0.25),
legend.text.align = 0,
legend.box = 'horizontal',
legend.margin = unit(45.0, 'line'),
legend.text=element_text(size=28,vjust=0,hjust=0),
legend.key.height = unit(1.5, 'line'),
legend.key.width = unit(1.5, 'line'),
panel.background = element_rect(fill = "white")) +
scale_color_manual(values=c('grey10','grey30','grey50'),
labels=c(expression(TI[d]),expression(TI[l]),
expression(TI[w]))) +
guides(color = guide_legend(title=NULL)) +
geom_vline(data=meanALLDTI, aes(xintercept=values.mean, colour=type),
linetype="dashed", size=1, show_guide=T) +
scale_linetype_manual(values=c('grey10','grey30','grey50'),
labels=c(expression(bar(TI[d])),expression(bar(TI[l])),
expression(bar(TI[w])))) +
guides(linetype= guide_legend(title=NULL))
Plot:
As an example of what I want, here is how it came out for me with density plots:
After some trial and error, I think it's better to use geom_segment in order to get a nice legend. With:
ggplot(allDTI, aes(x=values, color=type)) +
stat_ecdf(size=1) +
geom_segment(data=meanALLDTI, aes(x=values.mean, xend=values.mean, y=0, yend=1, color=type, linetype = type), size=1) +
labs(title=expression(TI[d]~'and'~TI[l]~'and'~TI[w]), x="Index Value", y="Cumulative Density") +
scale_x_continuous(expand = c(0,0)) +
scale_y_continuous(expand = c(0,0)) +
scale_color_manual(values=c("grey10", "grey30", "grey50"),
labels=c(expression(TI[d]),expression(TI[l]),expression(TI[w]))) +
scale_linetype_manual(values=c(3,2,5),
labels=c(expression(TI[d]),expression(TI[l]),expression(TI[w]))) +
guides(color = guide_legend(title="color",
override.aes = list(color = c("grey10", "grey30", "grey50"),
size = 2)),
linetype = guide_legend(title="lty", override.aes = list(linetype = c(3,2,5),
size = 0.7))) +
theme(text = element_text(size=20),
plot.title = element_text(size=30,face="bold",vjust=1),
axis.title.x = element_text(size=20,face="bold",vjust=0,hjust=0.5),
axis.title.y = element_text(size=20,face="bold",vjust=1.0,hjust=0.5),
legend.position = c(0.85, 0.25),
legend.box = 'horizontal',
legend.title = element_blank(),
legend.text.align = 0,
legend.text = element_text(size=20,vjust=0,hjust=0),
legend.key = element_rect(fill=NA),
legend.key.height = unit(1.5, 'line'),
legend.key.width = unit(1.5, 'line'),
panel.background = element_rect(fill = "white"))
you get:

Add legend to ggplot object (why two legends?)

I created a ggplot2 object:
a <- replicate(8,rnorm(100))
colnames(a) <- letters[1:8]
b < -melt(a,id.vars=1:1)
colnames(b) <- c("c","variable","value")
ggplot(b,aes(x = c,y = value, colour = variable, linetype = variable)) +
geom_line()+
geom_point(aes(shape = factor(variable)), size = 1.7) +
scale_x_continuous(limits = c(-1, 1),
breaks = seq(-1, 1, 0.1),
expand=c(0.01, 0.01)) +
scale_y_continuous(limits = c(-1, 1),
breaks = seq(-1, 1, 0.1),
expand = c(0.01, 0.01))+
theme_bw(base_size = 12, base_family = "Helvetica") +
theme(axis.text=element_text(size = 10),
axis.title=element_text(size = 10),
text = element_text(size = 10),
axis.line = element_line(size = 0.25),
axis.ticks=element_line(size = 0.25),
panel.grid.major = element_blank(),
#panel.grid.minor = element_blank(),
panel.border = element_rect(colour = "black", fill = NA, size = 0.5),
panel.background = element_blank(),
legend.position = "top" ,
legend.direction = "vertical",
legend.title = element_blank(),
legend.text = element_text(size = 13),
legend.background = element_blank(),
legend.key = element_blank()) +
labs(x = '', y = '', title = "") +
theme(plot.title = element_text(size=10)) +
theme(strip.text.x = element_text(size = 8,color="black"),
strip.background = element_blank()) +
theme(strip.text.x = element_text(size = 8, colour = "black"))
My problem is the following:
when I create the legend, there is a separate legend for the colors and a separate one for the points.
How can I create a single legend for each of the 8 variables?
Let me minimise your code and focus on the legend issue. This is what you have now.
ggplot(b,aes(x = c, y = value, colour = variable, linetype = variable)) +
geom_line() +
geom_point(aes(shape = factor(variable)),size=1.7)
Your data frame, b has variable as factor. You use this in two ways here; variable and factor(variable). You can simply use variable for shape in geom_point; make all variable identical.
ggplot(b,aes(x = c, y = value, colour = variable, linetype = variable)) +
geom_line()+
geom_point(aes(shape = variable),size = 1.7)
I saw some warning messages related to colours and other things. You may want to take care of them. But, for legend, this is one way to go.
Take from the ideas on this page: http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/#modifying-the-text-of-legend-titles-and-labels
I edited your code to make the data visible (you had problems with your x-axis limits. Note the final three lines. These commands tell ggplot to create only one legend.
a<-replicate(6,rnorm(100))
colnames(a)<-letters[1:6]
b<-melt(a,id.vars=1:1)
colnames(b)<-c("c","variable","value")
ggplot(b,aes(x=c,y=value,colour=variable,linetype=variable)) +
geom_line() + geom_point(aes(shape=factor(variable)),size=1.7)+
scale_x_continuous(limits=c(0,100))+
scale_y_continuous(limits=c(-2,2),breaks=seq(-2,2,0.1),expand=c(0.01,0.01))+
theme_bw(base_size=12, base_family="Helvetica") +
theme(axis.text=element_text(size=10),
axis.title=element_text(size=10),
text = element_text(size=10),
axis.line = element_line(size=0.25),
axis.ticks=element_line(size=0.25),
panel.grid.major = element_blank(),
#panel.grid.minor = element_blank(),
panel.border = element_rect(colour="black",fill=NA,size=0.5),
panel.background = element_blank(),
legend.position="top" ,
legend.direction="vertical",
legend.title=element_blank(),
legend.text=element_text(size=13),
legend.background=element_blank(),
legend.key=element_blank())+
labs(x='', y='',title="")+
theme(plot.title=element_text(size=10))+
theme(strip.text.x = element_text(size = 8,color="black"),strip.background=element_blank())+
theme(strip.text.x = element_text(size = 8,color="black"))+
scale_colour_discrete(name ="Factor")+
scale_linetype_discrete(name ="Factor") +
scale_shape_discrete(name ="Factor")

Resources