Legend for additional points in a ggplot - r

Steeling the example of this question (Link), I want to ask if it is possible to add the additional blue point to the legend?
dat <- data.frame(cond = rep(c("A", "B"), each=10),
xvar = 1:20 + rnorm(20,sd=3),
yvar = 1:20 + rnorm(20,sd=3))
g1 <- dat[15,]
ggplot(dat, aes(x = xvar, y = yvar, shape = cond,
colour = cond), size = 2.5) +
geom_point(alpha = 1) +
geom_point(data = g1, colour = "blue", size = 4, show_guide = FALSE)

You can put the aesthetics for the additional points layer inside aes instead of outside to get it added to the legend. You can use any string value; that string will be the name in the legend.
Then you can control the color and shape of that point via scale_*_manual layers.
I additionally changed the size of that point in the legend using override.aes, which is optional.
ggplot(dat, aes(x = xvar, y = yvar, shape = cond,
colour = cond), size = 2.5) +
geom_point(alpha = 1) +
geom_point(data = g1, aes(colour = "Point 15", shape = "Point 15"), size = 4) +
scale_shape_manual(values = c(16, 17, 17) ) +
scale_color_manual(values = c("pink", "turquoise", "blue") ) +
guides(color = guide_legend( override.aes = list(size = c(1.5, 1.5, 4) ) ) )

You probably have to change the condition of that point in the data as in your example or add it to the date, if it is not already part of it.
dat <- data.frame(cond = rep(c("A", "B"), each=10),
xvar = 1:20 + rnorm(20,sd=3),
yvar = 1:20 + rnorm(20,sd=3))
dat$size = 2.5
dat[15,]$cond = "C"
dat$cond = as.character(dat$cond)
dat[15,]$size = 4
ggplot(dat, aes(x = xvar, y = yvar, shape = cond,
colour = cond, size=size)) +
geom_point(alpha = 1) +
scale_colour_manual(values=c("red", "turquoise", "blue")) +
scale_size_continuous(guide = FALSE)

Related

Swap key and label in ggplot legend

I have a plot like this:
library("ggplot2")
library("ggtext")
df = data.frame(x = rnorm(n=12), y = rnorm(n=12),
groupshape = rep(c("a","b","c"), 4),
groupcol = rep(c("e","d","f"), 4))
p = ggplot(df, aes(x = x,y = y,
shape = groupshape,
color = groupcol)) +
geom_point() + theme_classic() + labs(shape = "shape", color = "color")
Producing a plot like this:
But I want to know how to get something like this with the legend:
How would I do that? I can get rid of the shape itself through guides by turning them all while, but then the text just hovers menacingly without alignment to the legend below.
This could be achieved via the label.position and the label.theme arguments of guide_legend:
library("ggplot2")
library("ggtext")
df = data.frame(x = rnorm(n=12), y = rnorm(n=12),
groupshape = rep(c("a","b","c"), 4),
groupcol = rep(c("e","d","f"), 4))
ggplot(df, aes(x = x,y = y,
shape = groupshape,
color = groupcol)) +
geom_point() + theme_classic() + labs(shape = "shape", color = "color") +
guides(color = guide_legend(label.position = "left", label.theme = element_text(face = "bold")),
shape = guide_legend(label.position = "left"))

Defining Legends using ggplot

I am trying to define the legends of my plot in R.
I have the following code, this is a demo only, real data will have 7-8 columns and up to 20 samples
library(ggplot2)
library(RColorBrewer)
colors <-brewer.pal(n = 3, name = 'Paired')
ids <- c("TestA", "TestB", "TestC")
bg <-c(23, 13, 15)
sample1 <- c(21,15,17)
sample2 <- c(27,25,11)
sample3 <- c(24,14,18)
df <- data.frame(ids, bg, sample1,sample2,sample3)
ggplot(df) +
geom_col(aes(x = ids, y = bg), size = 1, color = "grey", fill = "grey") +
geom_point(aes(x = ids, y = sample1), size = 10, color=colors[1], group = 1) +
geom_point(aes(x = ids, y = sample2), size = 10, color=colors[2], group = 1) +
geom_point(aes(x = ids, y = sample3), size = 10, color=colors[3], group = 1)+
ggtitle("Plot title") +
xlab("x label") + ylab(" y label") +
scale_colour_manual(values = c("95% PI"= "black",
"Forecasts" = "red",
"Threshold" = "green"))
It produces the following output
How can I add legends like the following picture, and ensure that the color matches, i.e. legend color matches sample or bg color
Is this something like what you want?
ggplot(df) +
geom_col(aes(x = ids, y = bg, fill = "background"), size = 1, color = "grey") +
geom_point(data = df %>% pivot_longer(cols = starts_with("sample"), names_to = "sample", values_to = "values"), aes(x = ids, y = values, color = sample), size = 10) +
ggtitle("Plot title") +
xlab("x label") + ylab(" y label") +
scale_colour_manual(name = NULL, values = c("sample1"= "black",
"sample2" = "red",
"sample3" = "green"),
labels = c("95% PI", "forecasts", "Threshold")) +
scale_fill_manual(name = NULL, values = c("background" = "grey"))

Display ggplot legend correctly for line/shape combinations

I am trying to create a plot for three groups using three different coloured lines but only two of the groups have point markers. I can get the plot to display correctly but the legend shows the same point markers for all three groups.
I have created a reproducible example using the mpg dataset
library(tidyverse)
ggplot(mpg) +
geom_line(mapping = aes(x = displ, y = cty, color = drv), size = 1) +
geom_point(data = subset(mpg, drv != '4'), mapping = aes(x = displ, y = cty, color = drv, shape = drv), size = 3) +
scale_color_manual(name="Variable", labels = c("4", "f", "r"), values=c("4" = "#DA2128", "f" = "black", "r" = "blue")) +
scale_shape_manual(name="Variable", labels = c("f", "r"), values = c("f" = 16, "r" = 17), guide = FALSE)
The group '4' should have no point marker in the legend and the group 'r' should show a triangle marker
Thanks in advance for your help
Try some alpha
ggplot(mpg, aes(x = displ, y = cty, color = drv, shape = drv)) +
geom_line() +
geom_point(aes(alpha=drv), size = 3) +
scale_alpha_manual(values = c(0,1,1)) +
scale_shape_manual(values = c(1,16, 17))
Or simply set shape 4 to NA
ggplot(mpg, aes(x = displ, y = cty, color = drv, shape = drv)) +
geom_line() +
geom_point(size = 3) +
scale_shape_manual(values = c(NA, 16, 17)) +
scale_color_manual(values = c("#DA2128", "black", "blue"))
Adding linetype argument in your geom_line() with the variable of interest (drv in this case) gives your expected result.
library(tidyverse)
ggplot(mpg) +
geom_line(mapping = aes(x = displ, y = cty, color = drv, linetype = drv), size = 1) +
geom_point(data = subset(mpg, drv != '4'), mapping = aes(x = displ, y = cty, color = drv, shape = drv), size = 3) +
scale_color_manual(name="Variable", labels = c("4", "f", "r"), values=c("4" = "#DA2128", "f" = "black", "r" = "blue")) +
scale_shape_manual(name="Variable", labels = c("f", "r"), values = c("f" = 16, "r" = 17), guide = FALSE)
You could also disable the legend for shape and set the values for shape manually in the color legend:
ggplot(mpg) +
geom_line(mapping = aes(x = displ, y = cty, color = drv), size = 1) +
geom_point(data = subset(mpg, drv != '4'), mapping = aes(x = displ, y = cty, color = drv, shape = drv), size = 3) +
scale_color_manual(name="Variable", labels = c("4", "f", "r"), values=c("4" = "#DA2128", "f" = "black", "r" = "blue"), guide=guide_legend(override.aes = list(shape = c("4" = NA, "f" = 16, "r" = 17)))) +
scale_shape_manual(values = c("f" = 16, "r" = 17), guide=F)

Additional legend in ggplot2

I have a problem where the legend of my ggplot() does not appear. Here's my code:
plot_bt <- ggplot(NULL, aes(x, v1)) +
geom_line(data = nig_bt_1, colour = "black") +
geom_line(data = nig_bt_2, colour = "blue") +
geom_line(data = nig_bt_3, colour = "red") +
labs(x = "X", y = "Probability")
I tried to make a legend inside this graph but I could not do it. It just does not appear. I try to make a plot of three different types of NIG distribution. In nig_bt_1 etc. I have my values. Those three densities appear but the legend doesn't. I tried the scale_color_manual function too with no success.
Thank you very much.
x <- seq(-7.5,7.5,0.001)
nig_bt_1 <- data.frame(x ,v1 = dnig(x, param = pr_bt_1))
nig_bt_2 <- data.frame(x ,v1 = dnig(x, param = pr_bt_2))
nig_bt_3 <- data.frame(x ,v1 = dnig(x, param = pr_bt_3))
Just do this:
plot_bt <- ggplot(NULL, aes(x, v1)) +
geom_line(data = nig_bt_1, aes(colour = "a")) +
geom_line(data = nig_bt_2, aes(colour = "b")) +
geom_line(data = nig_bt_3, aes(colour = "c")) +
labs(x = "X", y = "Probability") +
scales_color_manual(values= c("a" = "black", "b" = "blue", "c" = "red"))
A guide can only depict mappings you've defined using aes. The ggplot2 way is of course to first combine the data and use a grouping variable.

How do I remove the _printed_ output warnings using ggplot2 with knitr

GGplot2 prints out a warning when using scale_colour_gradient twice in a plot, which I cannot suppress in knitr. Here is a screenshot of my browser after knitting an RHTML file:
I need to colour gradients, one for the line (cheap / dear of yield curve) and one for the instruments which is similar but subtly different (coloured dots).
Here is my ggplot code:
ggp <- ggplot(polys, aes(x = xvals, y = yvals)) +
#geom_polygon(aes(fill = - value, group = id, alpha = value)) + # lovely blue
geom_polygon(aes(fill = value, group = id, alpha = value)) + # lovely shiny light blue middle draw me in
scale_x_log10(breaks = xaxtickpos, minor_breaks = NULL) +
theme(legend.position = "none", panel.background = element_rect(fill = "grey85", colour = NA)) +
xlab("maturity") + ylab("bps")
ggp <- ggp + geom_line(data = quanmelt[quanmelt[, "percentile"] %in% outerthresh, ],
aes(x = mat, y = value, group = percentile), colour = "white", size = 2)
ggp <- ggp + geom_line(data = quanmelt[quanmelt[, "percentile"] %in% innerthresh, ],
aes(x = mat, y = value, group = percentile), colour = "white", size = 1,
linetype = "dotted")
#add last few days line/today (this doesn't work very well hence commented out)
todayback <- todayline[todayline$daysback == 2, ] # get this historic lines
ggp <- ggp + geom_smooth(data = todayback, aes(x = mat, y = value, group = daysback),
colour = "darkred", linetype = "dashed",
se = FALSE, size = 1, method = "loess", span = (ifelse(smooth, 0.3, 0.1)))
#add boxplot
ggp <- ggp + geom_boxplot(data = meltcdlong, aes(x = mat, y = value, group = bond), outlier.size = NA,
colour = "grey30", alpha = 0.5, size = 0.2, width = 0.025)
# add the latest point
ggp <- ggp + geom_point(data = latestcdpoint, aes(x = mat, y = value, group = bond))
# now do labels (twice - one for above, one for below)
ggp <- ggp + geom_text(data = latestcdpoint[latestcdpoint$adjustvertvec == 1, ], aes(x = mat, y = labelposies, label = label),
angle = 90, colour = "grey20", size = 3, hjust = 0, alpha = 0.5)
ggp <- ggp + geom_text(data = latestcdpoint[latestcdpoint$adjustvertvec == 0, ], aes(x = mat, y = labelposies, label = label),
angle = 90, colour = "grey20", size = 3, hjust = 1, alpha = 0.5)
#now print a nice z-score graded colour line for the curve
todaytoday <- todayline[todayline$daysback == 0, ]
minz <- min(rescale(todaytoday[, "zscore"])) # for scaling of z-score line gradient colours
maxz <- max(rescale(todaytoday[, "zscore"]))
bpspline <- smooth.spline(todaytoday$mat, todaytoday$value, spar = 0.4) # Smooth out the curve with lots of points
zscorespline <- smooth.spline(todaytoday$mat, todaytoday$zscore) # and smooth out the zscores too
xplot <- seq(2, maxmat, by = 0.1)
todayplotter <- data.frame(mat = xplot, value = predict(bpspline, xplot)$y,
zscore = rescale(c(-5, 5, predict(zscorespline, xplot)$y))[-1:-2]) # build the plotter
ggp <- ggp + geom_path(data = todayplotter, aes(x = mat, y = value, colour = zscore), size = 2, linejoin = "bevel") +
scale_colour_gradientn(colours = gradientcolours, values = gradientscale, limits = c(minz, maxz))
#and the title
ggp <- ggp + ggtitle(cCode)
# now the test chart
mm <<- meltcdrecent[meltcdrecent$daysback == 0, ]
ggp <- ggp + geom_point(data = mm, aes(x = mat, y = value, colour = rescale(c(-5, 5, zscore))[-1:-2]), size = 6) +
scale_colour_gradientn(colours = gradientcolours, values = gradientscale, limits = c(0, 1))
ggp <- ggp + geom_point(data = mm, aes(x = mat, y = value), colour = "black", size = 4.5)
ggp <- ggp + geom_text(data = mm, aes(x = mat, y = value), label = round(mm$zscore, 1), colour = "white", size = 2, alpha = 0.7)
It's quite complex, but you can see I have two scale_colour_gradient(s).
Here is my knitr code:
<!--begin.rcode changer, echo=FALSE, fig.height=4.5, fig.width=8
for(x in ac) {
g <- ggCD(x, plotit = FALSE)
suppressWarnings(plot(g$cdChart))
}
end.rcode-->
I would like either to get rid of these warnings (they're not actual real warnings, so suppressWarnings doesn't work), or else, use scale_colour_gradient in a way which does not produce this text in the first place.
Change
<!--begin.rcode changer, echo=FALSE, fig.height=4.5, fig.width=8
into
<!--begin.rcode changer, echo=FALSE, fig.height=4.5, fig.width=8, message=FALSE

Resources