Broken confidence interval areas when using ylim in ggplot2 - r

I've been using ggplot2 for long, but never experienced this issue. I am representing confidence intervals of some regressions. However, I decided to manually control the ylim(). I realized that those areas which exceed the y limits are broken. See this picture:
The red regression on the right contains a very wide CLs. As you can see there is a gap in there as its highest point is outside ylim range.
This is the code I used:
ggplot(dataset, aes(x=variable, y=value, fill=Species, colour=Species, linetype = Species)) +
geom_smooth(method="lm", formula= y~poly(x,3), level=0.95, alpha=0.2) +
xlab("A") +
ylab("B") +
ylim(0, 30) +
theme(axis.text.x = element_text(angle = 0, hjust = 0.5, size = 10),
panel.background = element_blank(),
legend.position='bottom',
panel.grid.major = element_line(colour="azure2"),
axis.line = element_line(colour = "black",
size = 0.15, linetype = "solid")) +
scale_x_continuous(breaks=seq(1, 10, 1), limits=c(1, 10)) +
scale_color_manual(values=c("coral4", "coral1", "darkolivegreen3", "darkgoldenrod4", "darkgoldenrod2", "deepskyblue3", "darkorchid3")) +
scale_fill_manual(values=c("coral4", "coral1", "darkolivegreen3", "darkgoldenrod4", "darkgoldenrod2", "deepskyblue3", "darkorchid3")) +
scale_linetype_manual(values=c(1,1,1,3,3,2,2))
I would like to keep these y limits. I used coord_cartesian with no success. Can anybody help me?

coord_cartesian should work, but you have to remove the ylim()
Some data
set.seed(1)
df <- data_frame(x = -5:5, y = rnorm(11, x^2, 5))
Replicating your problem
ggplot(df, aes(x, y)) +
geom_smooth() +
ylim(-1, NA)
With coord_cartesian
ggplot(df, aes(x, y)) +
geom_smooth() +
coord_cartesian(ylim = c(-1, 40))

Related

How to draw an inclined line and parallelly put the text on it in ggplot?

Now, I'm making some hypothesis graph and I made this graph.
x<- c(1,2,3,4,5,6,7,8,9,10,11)
y<- c(100,90,80,70,60,50,40,30,20,10,1)
a<- c(1,2,3,4,5,6,7,8,9,10)
b<- c(1,4,9,16,25,36,49,64,81,100)
dataA<- data.frame (x,y)
dataB<- data.frame (a,b)
geom_line(data=dataA, aes(x=x, y=y), col="Dark red", size=1) +
geom_line(data=dataB, aes(x=a, y=b), col="Dark blue", size=1) +
scale_x_continuous(breaks = seq(0,12,1), limits = c(0,12)) +
scale_y_continuous(breaks = seq(0,120,10), limits = c(0,120)) +
geom_hline(yintercept=70, linetype="dashed", color = "Black", size=1) +
geom_hline(yintercept=50, linetype="dashed", color = "Black", size=1) +
#geom_text(aes(fontface=6), x=11, y=110, label=paste("% distal\n","grains"), size=6, col="Dark blue") +
geom_text(aes(fontface=6), x=10, y=75, label="AGW (90th percentile)", size=5, col="Black") +
geom_text(aes(fontface=6), x=10, y=55, label="AGW (10th percentile)", size=5, col="Black") +
xlab(bquote('x ('~m^2*')')) +
ylab(bquote('y (mg '~grain^-1*')')) +
theme(axis.title = element_text (face = "plain", size = 18, color = "black"),
axis.text.x = element_blank(), #element_blank()) element_text(size= 14)
axis.text.y = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
axis.line = element_line(size = 0.5, colour = "black"))+
windows(width=5.5, height=5)
As an alternatives, I need to present such as below graph, but I don't know how to draw an inclined line, starting a specific point of y-axis. Also, I would like to add a text on the line in a parallel position. Could you tell me how I can do this?
Many thanks!!
Here is a concrete example based on #Waldi 's comment:
library(ggplot2)
# Change line to what you want
line <- data.frame(x = c(10,30), y = c(300,50))
line = lm(formula = line$y ~ line$x)$coefficients
# ratio required for unequal axis scales
ratio <- 1/15
# get angle of the line
angle <- atan(line[2] * ratio) * 180 / pi
# plot it
ggplot(mtcars, aes(x = mpg, y = hp)) +
geom_point() +
geom_abline(slope = line[2], intercept = line[1], color = "blue") +
coord_equal(ratio = ratio) +
annotate(
geom = "text",
x = 20,
y = 20 * line[2] + line[1],
label = "My Line",
color = "blue",
angle = angle,
vjust = -1 # offset so text isn't directly on the line
)

How to add a second legend using different `geom_line`?

I am plotting the relationship between two variables (X and Y) for different individuals (IDs). This relationship is shown both with the real values (geom_point) and with lines which represent the prediction of the relationship between the variables for different individuals Linear Mixed Effect Models (LME). On top of that, the linear relationship between the two variables and for the different individuals is done using three levels of a second quantitative predictor (Z).
Thus, what I do is to use geom_point() for showing the relationship between raw values of X and Y. Then, I use three geom_line() for three LME with different levels of Z. Thus, each geom_line() draws the six lines for the six IDs for a fixed Z. So, since I have 3 Z levels and I have 3 geom_line(), I have 18 lines.
I tried this (note: code is simplified):
Plot_legend <- ggplot(df, aes(x=X, y=Y, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_line(aes(y=predict(model,df.Z_low), group=ID, linetype = c("1")), size=1.5, alpha=0.6, color = line_colors[3]) +
geom_line(aes(y=predict(model,df.Z_medium), group=ID, linetype = c("2")), size=1.5, alpha=0.6, color = line_colors[2]) +
geom_line(aes(y=predict(model,df.Z_high), group=ID, linetype = c("3")), size=1.5, alpha=0.6, color = line_colors[1]) +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
theme(legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold",hjust = 0.5),
legend.key=element_blank(),
legend.background = element_rect(colour = 'black', fill = 'white', size = 1, linetype='solid')) +
guides(color=guide_legend(override.aes=list(fill=NA)))
However, as you can see, the legend for the three geom_line() is not what I desire. I would like to appear as title Z instead of c("10th"). Also, the colours of the legend for the three geom_line() do not correspond with the true colours for the different geom_line(), and some lines are dashed.
Does anyone know how to solve this?
Plot using Duck's advice
Try this approach. As no data was shared I can test it but it can address in right path:
library(ggplot2)
#Code
Plot_legend <- ggplot(df, aes(x=X, y=Y, colour=ID)) +
geom_point(size=1.5,alpha=0.2) +
geom_line(aes(y=predict(model,df.Z_low), group=ID, linetype = c("1")),
size=1.5, alpha=0.6, color = line_colors[3]) +
geom_line(aes(y=predict(model,df.Z_medium), group=ID, linetype = c("2")),
size=1.5, alpha=0.6, color = line_colors[2]) +
geom_line(aes(y=predict(model,df.Z_high), group=ID, linetype = c("3")),
size=1.5, alpha=0.6, color = line_colors[1]) +
geom_abline(aes(slope=1,intercept=0),linetype="dashed",color="grey52",size=1.5) +
theme_bw() +
scale_linetype_manual(values=c('solid','solid','solid'))+
scale_color_manual(values=c(line_colors[3],line_colors[2],line_colors[1]))+
labs(linetype='Z')
theme(legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold",hjust = 0.5),
legend.key=element_blank(),
legend.background = element_rect(colour = 'black', fill = 'white', size = 1, linetype='solid')) +
guides(color=guide_legend(override.aes=list(fill=NA)))
I used next code finally:
Plot_legend <- ggplot(df, aes(x=X, y=Y, 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(legend.text=element_text(size=18),
legend.title = element_text(size=19, face = "bold",hjust = 0.5),
legend.key=element_blank(),
legend.background = element_rect(colour = 'black', fill = 'white', size = 1, linetype='solid')) +
guides(color=guide_legend(override.aes=list(fill=NA)))
Plot_legend
Plot_legend_2 <- Plot_legend +
geom_line(aes(y=predict(model,df.Z_low), group=ID, linetype = "m1"), size=1.5, alpha=0.6, color = line_colors[3]) +
geom_line(aes(y=predict(model,df.Z_medium), group=ID, linetype ="m2"), size=1.5, alpha=0.6, color = line_colors[2]) +
geom_line(aes(y=predict(model,df.Z_high), group=ID, linetype ="m3"), size=1.5, alpha=0.6, color = line_colors[1]) +
scale_linetype_manual(values = c(m1 = "solid", m2 = "solid", m3 = "solid"),labels = c(m1 = "1", m2 = "2", m3 = "3")) +
labs(color = "ID", linetype = expression(Z)) +
guides(linetype = guide_legend(override.aes = list(color = line_colors)))
Plot_legend_2

Scale the distance between ticks on x-axis in gglot r

I have a graph like this. I am interested in the minor change between the range (-3.5, 0.5), however, the occupied only a small portion of the x-axis, so that it's hard to interpret.
I tried to use transform to log scale for better visualization, however, it apparently not works for negative values.
So is there any method to expand this region to make the graph look nicer?
Code:
ggplot() + geom_line(data = Final_diction, aes(x = Final_diction[,1], y
= Final_diction[,4])) +
xlim(-3.5,20) +
geom_vline(xintercept=c(-0.5,0.5), linetype="dashed", color = "red") +
geom_vline(xintercept=c(-0.25,0.25), linetype="dashed", color = "blue") +
theme_bw() +
theme(axis.title = element_text(size = 20)) +
theme(axis.text = element_text(size = 18))
Something like this
library(ggforce)
library(ggolot2)
ggplot(mtcars, aes(x=mpg, y=disp, group=1)) +
geom_line() + facet_zoom(xlim = c(15, 20))
You may try adding the xlim = c(minor value, major value) option of ggplot, and use the range which works better for you
Something like that:
ggplot() + geom_line(data = Final_diction, aes(x = Final_diction[,1], y
= Final_diction[,4])) +
xlim(-3.5,20) +
geom_vline(xintercept=c(-0.5,0.5), linetype="dashed", color = "red") +
geom_vline(xintercept=c(-0.25,0.25), linetype="dashed", color = "blue") +
theme_bw() +
theme(axis.title = element_text(size = 20)) +
theme(axis.text = element_text(size = 18)) +
xlim = c(-4, 1)

ggplot2: change strip.text position in facet_grid plot

you can set the position of the legend inside the plotting area, like
... + theme(legend.justification=c(1,0), legend.position=c(1,0))
Is there a similarly easy way to change the position of the strip text
(or factor levels in grouped plots)
library(reshape2); library(ggplot2)
sp <- ggplot(tips, aes(x=total_bill, y=tip/total_bill)) + geom_point() +
facet_grid(. ~ sex)
sp
(http://www.cookbook-r.com/Graphs/Facets_%28ggplot2%29/)
in lattice I would use something like strip.text = levels(dat$Y)[panel.number()]
and panel.text(...), but there may be a cleaner way too...
thx, Christof
Here's one approach:
ggplot(tips, aes(x = total_bill, y = tip / total_bill)) +
geom_point() +
facet_grid(. ~ sex) +
geom_text(aes(label = sex), x = Inf, y = Inf, hjust = 1.5, vjust = 1.5) +
theme(
strip.background = element_blank(),
strip.text = element_blank()
)
However, this is not moving the strip.text, rather, it's adding a geom_text element and turning off the strip.background and strip.text, but I think it achieves the desired outcome.
A slight addition to #JasonAizkalns is to add the check_overlap = T option in geom_text, to avoid the superposition of multiple identical labels.
ggplot(tips, aes(x = total_bill, y = tip / total_bill)) +
geom_point() +
facet_grid(. ~ sex) +
geom_text(aes(label = sex), x = Inf, y = Inf, hjust = 1.5, vjust = 1.5, check_overlap = TRUE) +
theme(
strip.background = element_blank(),
strip.text = element_blank()
)

Overlay density of one variable on trend line

I have some data:
dat <- data.frame(x=rnorm(100,100,100),y=rnorm(100,100,100))
I can plot it with a local trend line:
ggplot(dat, aes(x,y)) + stat_smooth()
But I want to overlay a density curve, on the same plot, showing the distribution of x. So just add the previous graph to this one (the y-axis is different, but I only care about relative differences in the density curve anyway):
ggplot(dat, aes(x)) + geom_density()
I know there's stat_binhex() and stat_sum() etc showing where the data falls. There are only a few y values, so what gets plotted by stat_binhex() etc is hard to read.
You can plot a combination of histograms and density curves at both sides of the scatterplot. In the example below I also included a confidence ellipse:
require(ggplot2)
require(gridExtra)
require(devtools)
source_url("https://raw.github.com/low-decarie/FAAV/master/r/stat-ellipse.R") # in order to create a 95% confidence ellipse
htop <- ggplot(data=dat, aes(x=x)) +
geom_histogram(aes(y=..density..), fill = "white", color = "black", binwidth = 2) +
stat_density(colour = "blue", geom="line", size = 1.5, position="identity", show_guide=FALSE) +
scale_x_continuous("x-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
scale_y_continuous("Density", breaks=c(0.0,0.01,0.02), labels=c(0.0,0.01,0.02)) +
theme_bw() + theme(axis.title.x = element_blank())
blank <- ggplot() + geom_point(aes(1,1), colour="white") +
theme(axis.ticks=element_blank(), panel.background=element_blank(), panel.grid=element_blank(),
axis.text.x=element_blank(), axis.text.y=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank())
scatter <- ggplot(data=dat, aes(x=x, y=y)) +
geom_point(size = 0.6) + stat_ellipse(level = 0.95, size = 1, color="green") +
scale_x_continuous("x-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
scale_y_continuous("y-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
theme_bw()
hright <- ggplot(data=dat, aes(x=y)) +
geom_histogram(aes(y=..density..), fill = "white", color = "black", binwidth = 1) +
stat_density(colour = "red", geom="line", size = 1, position="identity", show_guide=FALSE) +
scale_x_continuous("y-var", limits = c(-200,400), breaks = c(-200,0,200,400)) +
scale_y_continuous("Density", breaks=c(0.0,0.01,0.02), labels=c(0.0,0.01,0.02)) +
coord_flip() + theme_bw() + theme(axis.title.y = element_blank())
grid.arrange(htop, blank, scatter, hright, ncol=2, nrow=2, widths=c(4, 1), heights=c(1, 4))
the result:

Resources