The plot below is to create a ggplot in which I show the relationship between two variables according to the raw data (points) and according to two different models (m1 and m3), from which I extract the coefficients and I drow two continuous lines. The grey line is just to show a relationship of 1:1.
line_colors <- RColorBrewer::brewer.pal(7, "Reds")[c(2,4,6)]
line_colors
Plot_a <- ggplot(Todo.6min, aes(x=VeDBA.V13AP, y=VeDBA.X16, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
theme(strip.background=element_blank(),
axis.title.x =element_blank(),
axis.title.y =element_blank(),
axis.text.x = element_text(angle = 0, hjust = 0.5,size = 15),
axis.text.y = element_text(angle = 0, hjust = 0.5,size = 15),
axis.line = element_line(),
panel.grid.major= element_blank(),
panel.grid.minor = element_blank(),
legend.position = "right",
legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold"),
legend.key=element_blank(),
panel.border = element_blank(),
strip.placement = "outside") +
guides(color=guide_legend(override.aes=list(fill=NA)))
Plot_a
Plot_b <- Plot_a +
geom_abline(aes(linetype = "m1"),slope = fixef(mod2b)[2] , intercept = fixef(mod2b)[1], color = line_colors[1], size=1.5) +
geom_abline(aes(linetype = "m3"),slope = fixef(mod2d)[2] + fixef(mod2d)[3], intercept = fixef(mod2d)[1], color = line_colors[2], size=1.5) +
scale_linetype_manual(values = c(m1 = "solid", m3 = "solid"),labels = c(m1 = "m1", m3 = "m3")) +
labs(color = "ID", linetype = expression(Model)) +
guides(linetype = guide_legend(override.aes = list(color = line_colors)))
Plot_b
My doubt is why I do not get a legend for the continuous lines although I used scale_linetype_manual for indicating that I wanted a legend in which appears "m1" and "m3" as legend.text.
Does anyone know where is the mistake?
My suggestion would be to manually populate the mapping of geom_abline(), and then cut the data so that it matches the number of lines you're drawing. Illustrated below with an inbuilt dataset.
library(ggplot2)
ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
geom_abline(aes(linetype = c("m1", "m3"),
slope = c(0.5, 0.75),
intercept = c(0, 0.5)),
data = iris[1:2,])
Created on 2020-11-06 by the reprex package (v0.3.0)
For your use case you'd have to substute slope = c(0.5, 0.75) by slope = c(fixef(mod2b)[2], fixef(mod2d)[2]), etc.
Related
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)
Considering the following data, I am able to generate a plot which describes how the risk of a react over a time interval changes.
risk_1 <- c(0.121,0.226,0.333,0.167,0.200,0.273,0.138,0.323,0.394,0.250,0.200,0.545,0.190,0.355,0.515,0.333,0.300,0.818)
risk_minus_SE <- c(0.060,0.114,0.198,0.047,0.057,0.097,0.072,0.186,0.247,0.089,0.057,0.280,0.109,0.211,0.352,0.138,0.108,0.523)
risk_plus_SE <- c(0.229,0.398,0.504,0.448,0.510,0.566,0.249,0.499,0.563,0.532,0.510,0.787,0.309,0.531,0.675,0.609,0.603,0.949)
Status <- rep(c(rep('With placebo',3),rep('With drug',3)),3)
durtn <- rep(c('(3-15]','(15-30]','(30-46]'),6)
react <- c(rep("x\u226516",6),rep("x\u226509",6),rep("x\u226504",6))
df1 <- data.frame(risk_1, risk_minus_SE, risk_plus_SE, Status, durtn, react)
dodge <- position_dodge(width=0.45)
ggplot(df1,aes(colour=react, y=risk_1, x=durtn)) +
geom_point(aes(shape=durtn), shape=16, size = 5, position=dodge) +
geom_errorbar(aes(ymin=risk_minus_SE, ymax=risk_plus_SE), position = dodge, width=0.5, size=1, lty=1) +
scale_colour_manual(values = c('black','red','blue')) +
facet_grid(~Status) +
scale_shape_manual(values = c(8,19))+
theme_bw() +
scale_x_discrete(limits=c('(3-15]','(15-30]','(30-46]')) +
coord_cartesian(ylim = c(0, 0.8)) +
theme(legend.position = c(.1, .85), legend.background = element_rect(colour = "black"),
plot.title = element_text(lineheight=1.5, face="bold", size=rel(1.5), hjust = 0.5),
panel.grid.major.x = element_blank(),
axis.text.x = element_text(vjust=0.5, size=16),
axis.text.y = element_text(vjust=0.5, size=16),
axis.title.y = element_text(size=20),
axis.title.x = element_text(size=20),
legend.text = element_text(size = 16, face = "bold"),
strip.text = element_text(size=25)) +
xlab("\ntime (min)") + ylab("Risk")
What I want to do is overlay a series of points at given x and y coordinates.
That being at With drug & durtn==(3,15], manually insert points at.....
Risk==0.5 for react=x≥04 in black
Risk==0.2 for react=x≥09 in red
Risk==0.0 for react=x≥16 in blue
Such that the desired output should look like
How does one use the geom_point() in combination with a facet_grid and dodge
First, you have to create a separate data frame that contains the data for the additional points.
dat <- data.frame(risk_1 = c(0.5, 0.2, 0),
react = levels(df1$react),
durtn = '(3-15]',
Status = 'With drug')
This new data frame dat can be used with geom_point to add an additional layer to the existing plot.
+ geom_point(data = dat, position = dodge, shape = 4, size = 5, show.legend = FALSE)
I have a graph where two legends are present. I need to change the size of the points of one of the legends.
I need to change the bullet size of "market type" in the legend. I use the example here but does not work for my graph.
My code is below:
k <- ggplot(subsetdf) + theme_bw() +
geom_point( aes(y=y, x=x, size =Total.Unit.Count, fill = region), shape=21)+
scale_colour_hue(aes(y=y, x=x),l=50) + # Use a slightly darker palette than normal
geom_text_repel (aes(y=y, x=x, label = rownames(subsetdf))) +
geom_smooth(aes(x=x, y=y),method=lm, # Add linear regression lines
se=FALSE) +
labs(y = "title", x = "title",
title = "title",
size = "size", fill = "fill")+
theme(plot.title = element_text (face = 'bold',size = 21,hjust = 0.5),
legend.text = element_text(size = 16),
legend.title = element_text(size = 18),
axis.title.x = element_text(size=20),
axis.title.y = element_text(size=20),
axis.text.x = element_text(size = 18,angle=45, hjust=1),
axis.text.y = element_text(size = 18,hjust = 1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())+
scale_size_continuous(range = c(3,8))+
guides(colour = guide_legend(override.aes = list(size=10)))
You used the fill aesthetic guide, not color. So that is the guide to override.
Below is an example with iris dataset, as you code is not reproducible.
library(ggplot2)
ggplot(iris) +
geom_point(aes(Sepal.Length, Petal.Length, size = Sepal.Width, fill = Species), shape = 21) +
guides(fill = guide_legend(override.aes = list(size=8)))
Thanks for the suggested duplicate, this is however not only about the labels, but is also about adjusting the points themselves so they do not overlap.
have a quick look at the plot below...
I need the coloured points, and their corresponding labels, to never overlap. They should be clustered together and all visible, perhaps with some indication that they are spaced and not 100% accurate, perhaps some sort of call out? Open to suggestions on that.
I've tried adding position = 'jitter' to both geom_point and geom_text, but that doesn't seem to be working (assume it is only for small overlaps?)
Ideas?
# TEST DATA
srvc_data <- data.frame(
Key = 1:20,
X = sample(40:80, 20, replace = T),
Y = sample(30:65, 20, replace = T)
)
srvc_data$Z <- with(srvc_data,abs(X-Y))
t1<-theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(size=.4)
)
main_plot <- ggplot(srvc_data, aes(x = X, y = Y),xlim=c(0,100), ylim=c(0,100)) +
t1 +
theme_bw() +
labs(x="X", y="Y") +
scale_x_continuous(limits = c(0, 100)) +
scale_y_continuous(limits = c(0, 100)) +
geom_abline(intercept = 0, slope = 1, colour="blue", size=34, alpha=.1)+
geom_abline(intercept = 0, slope = 1, colour="black", size=.2, alpha=.5,linetype="dashed")+
geom_point(size = 7, aes(color = Z), alpha=.7) +
scale_color_gradient("Gap %\n",low="green", high="red")+
coord_fixed()+
geom_text(aes(label=Key,size=6),show_guide = FALSE)
main_plot
Produces this plot (of course with your random data it will vary)
Thanks in advance.
Here's your plot with ggrepel geom_text_repel:
library(ggrepel)
# TEST DATA
set.seed(42)
srvc_data <- data.frame(
Key = 1:20,
X = sample(40:80, 20, replace = T),
Y = sample(30:65, 20, replace = T)
)
srvc_data$Z <- with(srvc_data,abs(X-Y))
t1<-theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
axis.line = element_line(size=.4)
)
ggplot(srvc_data, aes(x = X, y = Y),xlim=c(0,100), ylim=c(0,100)) +
t1 +
theme_bw() +
labs(x="X", y="Y") +
scale_x_continuous(limits = c(0, 100)) +
scale_y_continuous(limits = c(0, 100)) +
geom_abline(intercept = 0, slope = 1, colour="blue", size=34, alpha=.1)+
geom_abline(intercept = 0, slope = 1, colour="black", size=.2, alpha=.5,linetype="dashed")+
geom_point(size = 7, aes(color = Z), alpha=.7) +
scale_color_gradient("Gap %\n",low="green", high="red")+
coord_fixed()+
geom_text_repel(aes(label=Key,size=6),show_guide = FALSE)
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")