Adding custom legend after theme(legend.title=element_blank(), legend.position='none') - r

I have the following data:
set.seed(100)
vals <- rnorm(100)
groups <- c(rep('group a', 30), rep('group b', 70))
df <- data.frame('vals'=vals, 'groups'=groups)
I plot the distributions of vals within groups like this:
ggplot(df, aes(y=vals, x=groups, fill=groups)) +
geom_boxplot() +
theme_minimal() +
scale_fill_brewer(palette = "Set3") +
geom_hline(yintercept=0.5, color='red', lty='dashed', size=1) +
geom_hline(yintercept=-0.5, color='blue', lty='dashed', size=1) +
theme(legend.title=element_blank(), legend.position='none')
This produces the following picture.
I would like to include a legend for the blue and red horizontal lines but not for the boxplots. How do I do that?

You could use the aes of linetype for each geom_hline with scale_linetype_manual and say that the boxplot should not be shown like this:
set.seed(100)
vals <- rnorm(100)
groups <- c(rep('group a', 30), rep('group b', 70))
df <- data.frame('vals'=vals, 'groups'=groups)
library(ggplot2)
ggplot(df, aes(y=vals, x=groups, fill=groups)) +
geom_boxplot(show.legend = FALSE) +
theme_minimal() +
scale_fill_brewer(palette = "Set3") +
geom_hline(aes(yintercept=0.5, lty='red'), color='red', size=1) +
geom_hline(aes(yintercept=-0.5, lty='blue'), color='blue', size=1) +
scale_linetype_manual(name = "Legend", values = c(2, 2),
guide = guide_legend(override.aes = list(color = c("red", "blue"))))
Created on 2023-01-16 with reprex v2.0.2

Related

How change color after certain intervals in ggplot2?

I have following data:
dput(data)
I used following code to generate the plot:
p <- ggplot(data, aes(Zscore, ID))
p + geom_point(aes(colour=pval, size=Hit)) +
scale_color_gradientn(colours=rainbow(4), limits=c(0, 1)) +
geom_vline(xintercept=0, size=0.2, colour="blue", linetype="dotted") +
theme(panel.background=element_rect(fill="gray95", colour="gray95"),
panel.grid.major=element_line(size=0.1,linetype='solid', colour="gray90"),
panel.grid.minor=element_line(size=0.1,linetype='solid', colour="gray90"),
axis.title.y=element_blank()) +
expand_limits(x=c(-2,3)) +
scale_x_continuous(breaks=c(-3,-2,-1,0,1,2,3)) +
scale_y_discrete(limits=rev(data$ID))
in the output, I want to change the color (to green) of positive Zscore values. Also to increase the hit to 0,10,20,25,50....
The plot below is maybe not what is wanted.
To have the color change to green when the Z-score is positive means it should be mapped to Zscore, not to pval;
Also, the aesthetic size for lines was deprecated in ggplot2 3.4.0, I am using linewidth instead.
library(ggplot2)
p <- ggplot(data, aes(Zscore, ID))
p + geom_point(aes(colour = Zscore > 0, size = Hit)) +
scale_color_manual(
name = 'Z-score',
labels = c("Negative", "Positive"),
values = c(`FALSE` = 'red', `TRUE` = 'green')
) +
scale_size_continuous(breaks = c(0,10,20,25,50, 75, 100)) +
geom_vline(xintercept=0, linewidth=0.2, colour="blue", linetype="dotted") +
theme(panel.background=element_rect(fill="gray95", colour="gray95"),
panel.grid.major=element_line(linewidth=0.1,linetype='solid', colour="gray90"),
panel.grid.minor=element_line(linewidth=0.1,linetype='solid', colour="gray90"),
axis.title.y=element_blank()) +
expand_limits(x=c(-2,3)) +
# scale_x_continuous(breaks=c(-3,-2,-1,0,1,2,3, 4, 5, 6)) +
scale_x_continuous(name = 'Z-score', breaks = pretty(data$Zscore)) +
scale_y_discrete(limits=rev(data$ID))
Created on 2022-11-18 with reprex v2.0.2

Adding a centred overlaid title to a ggplot2 doughnut graph

I'm hoping to create a ggplot2 title overlaying a doughnut graph, with my reprex adapted this example from https://www.r-graph-gallery.com/128-ring-or-donut-plot.html.
# load library
library(ggplot2)
# Create test data.
data <- data.frame(
category=c("A", "B", "C"),
count=c(10, 60, 30)
)
# Compute percentages
data$fraction <- data$count / sum(data$count)
# Compute the cumulative percentages (top of each rectangle)
data$ymax <- cumsum(data$fraction)
# Compute the bottom of each rectangle
data$ymin <- c(0, head(data$ymax, n=-1))
# Compute label position
data$labelPosition <- (data$ymax + data$ymin) / 2
# Compute a good label
data$label <- paste0(data$count)
# Make the plot
ggplot(data, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) +
geom_rect() +
coord_polar(theta="y") + # Try to remove that to understand how the chart is built initially
xlim(c(2, 4))+ # Try to remove that to see how to make a pie chart
theme_void()+
scale_fill_brewer(palette = 1)+
geom_label( x=3.5, aes(y=labelPosition, label=label), size=6)+
theme(legend.position = "top",
plot.title = element_text(hjust=0.5))+
ggtitle("My title")
This is what I have currently:
And this is what I want:
I haven't been able to find any documentation demonstrating how to do this in ggplot2. Any suggestions are appreciated.
You can add an annotation layer :
library(ggplot2)
ggplot(data, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=category)) +
geom_rect() +
coord_polar(theta="y") +
xlim(c(2, 4))+
theme_void()+
scale_fill_brewer(palette = 1)+
geom_label( x=3.5, aes(y=labelPosition, label=label), size=6)+
theme(legend.position = "top") +
annotate('text', x = 2, y = 0.5, label = 'My title', color = 'blue', size = 5)

ggplot secondary axis wrong legend colours

I've been trying to create a plot with a secondary axis, but as you can see underneath, R changes all the line colours in the legend to blue, not just the one for the secondary axis:
library(ggplot2)
library(reshape2)
prev <- data.frame(
YEAR = seq(1990,1995),
GP = c(7,9,14,12,11,12),
HOSPITAL = c(0,0,0,0,0.5,0.8)
)
d <- melt(prev, id.vars="YEAR")
names(d)[2] <- "Datasets"
prev2 <- data.frame(
YEAR = seq(1990,1995),
Datasets = rep("REFERRALS",6),
value = c(0.5,0.9,1.2,3,7,11)
)
ggplot(d, aes(YEAR, value, linetype=Datasets), show.guide=FALSE) +
geom_line() +
scale_linetype_manual(values=c("solid","dashed","solid")) +
scale_x_discrete(limits=seq(1990,1995,1)) +
geom_vline(xintercept=1991, col="darkgrey") +
geom_vline(xintercept= 1994, col="darkgrey") +
geom_line(data=prev2, aes(y=value), col="blue") +
scale_y_continuous(sec.axis=sec_axis(~.*7,name="number of referrals")) +
theme_bw() + xlab("\nYear") + ylab("Prevalence") +
theme(legend.justification=c(.1,.9), legend.position=c(.05,.96),
legend.title=element_blank(),
plot.margin = unit(c(.5,.5,.5,.5), "cm"),
axis.title.y.right = element_text(color="blue"))
Does anyone know how to get the line colours in the legend back to black for "GP" and "HOSPITAL"?
You can control the color in the guide:
+ guides(linetype = guide_legend(override.aes = list(color = "red")))
Here I use red for highlighting that this works for arbitrary colors. You want of course color = c("black", "black", "blue").
Simply change the order of your calls to geom_line. Like so:
ggplot(d, aes(YEAR, value, linetype=Datasets), show.guide=FALSE) +
geom_line(data=prev2, aes(y=value), col="blue") +
geom_line() +
scale_linetype_manual(values=c("solid","dashed","solid")) +
scale_x_discrete(limits=seq(1990,1995,1)) +
geom_vline(xintercept=1991, col="darkgrey") +
geom_vline(xintercept= 1994, col="darkgrey") +
scale_y_continuous(sec.axis=sec_axis(~.*7,name="number of referrals")) +
theme_bw() + xlab("\nYear") + ylab("Prevalence") +
theme(legend.justification=c(.1,.9), legend.position=c(.05,.96),
legend.title=element_blank(),
plot.margin = unit(c(.5,.5,.5,.5), "cm"),
axis.title.y.right = element_text(color="blue"))

manual color assignment of a legend object in ggplot2

This is my code:
library(data.table)
library(ggplot2)
clist <- list(c(1:39), c(2:40), c(3:41))
clist.ts <- lapply(clist, function(x) ts(x, frequency = 1, start = 1978))
ind78_ymean_tsdf <- as.data.frame(clist.ts)
names(ind78_ymean_tsdf) <- c("name1", "name2", "name3")
ind78_ymean_tsdf$"Year" <- c(1978:2016)
setDT(ind78_ymean_tsdf)
ind78_ymean_melt <- melt(ind78_ymean_tsdf, id=c("Year"))
(ggplot(ind78_ymean_melt, aes(x=Year, y=value, color=variable))
+ geom_line()
+ geom_line(data=subset(ind78_ymean_melt, variable == "name1"), colour="black", size=1.5)
+ labs(title="Development of the indices", x="Year", y="Index")
+ scale_color_discrete(name="Individual replications")
+ theme_light())
# + guides(colour=guide_legend(override.aes=list(colour=c(hue_pal()(11)[1:10], "black"), size=c(rep(1, 10), 1.5))))
It is basically the same as in the following question, but with a reproducible example: manual color assignment
My problem is now, that I don't know how I had to change the following line in order to get the entry in the legend of the plot also black:
guides(colour=guide_legend(override.aes=list( colour=c(hue_pal()(11)[1:10], "black"), size=c(rep(1, 10), 1.5))))
Maybe someone could explain what the parameters in the line above mean or could post the question to the link above, because I have not enough street cred. to do so.. :) I have 13 variables in the real plot (not in the reproducible example above) if that helps. Thanks in advance!
Your solution looks overcomplicated. Why don't you simply scale_color_manual and scale_size_manual.
ggplot(ind78_ymean_melt, aes(Year, value, color = variable, size = variable)) +
geom_line() +
labs(title = "Development of the indices",
x = "Year",
y = "Index",
color = "Individual replications") +
scale_color_manual(values = c("black", hue_pal()(2))) +
scale_size_manual(values = c(1.5, rep(0.5, 2))) +
theme_light() +
guides(size = FALSE)
This is the solution from #drmariod:
(ggplot(ind78_ymean_melt, aes(x=Year, y=value, color=variable), size=2)
+ geom_line()
+ geom_line(data=subset(ind78_ymean_melt, variable == "name3"), colour="black", size=1.5)
+ labs(title="Development of the indices", x="Year", y="Index")
+ scale_color_discrete(name="Individual replications")
+ theme_light()
+ guides(colour=guide_legend(override.aes=list( colour=c(hue_pal()(2), "black"), size=c(rep(1, 2), 1.0)))) )
And the explanation of the last code line: the hue_pal()(11) creates 11 colours from the hue palette but it chooses only color 1:10 and adds a black color to it.

Deleting an entire row of facets of unused factor level combination

I want to remove the 2nd row of facets from my plot below because there is no data for that factor combination.
library(ggplot2)
library(grid)
set.seed(5000)
# generate first df
df1 = data.frame(x=rep(rep(seq(2,8,2),4),6),
y=rep(rep(seq(2,8,2),each=4),6),
v1=c(rep("x1",32),rep("x2",64)),
v2=c(rep("y1",64),rep("y2",32)),
v3=rep(rep(c("t1","t2"),each=16),3),
v4=rbinom(96,1,0.5))
# generate second df
df2 = data.frame(x=runif(20)*10, y=runif(20)*10,
v1=sample(c("x1","x2"),20,T))
# plot
ggplot() +
geom_point(data=df1, aes(x=x, y=y, colour = factor(v4)), shape=15, size=5) +
scale_colour_manual(values = c(NA,"black")) + facet_grid(v1+v2~v3, drop = T) +
geom_point(data=df2, aes(x=x,y=y), shape=23 , colour="black", fill="white", size=4) +
coord_equal(ratio=1) + xlim(0, 10) + ylim(0, 10)
I tried to use the idea from this post..
g=ggplotGrob(y)
pos=which(g$layout$t==5 | g$layout$t==6)
g$layout=g$layout[-c(pos),]
g$grobs=g$grobs[-c(pos)]
grid.newpage()
grid.draw(g)
..but got this.
How do I eliminate the white space? Also, is there a straightforward solution to this, without having to manipulate the grobs, etc?
Just modify the data:
df2 <- rbind(cbind(df2, v2 = "y1"),
cbind(df2, v2 = "y2"))
df2 <- df2[!(df2$v1 == "x1" & df2$v2 == "y2"),]
# plot
ggplot() +
geom_point(data=df1, aes(x=x, y=y, colour = factor(v4)), shape=15, size=5) +
scale_colour_manual(values = c(NA,"black")) + facet_grid(v1+v2~v3, drop = T) +
geom_point(data=df2, aes(x=x,y=y), shape=23 , colour="black", fill="white", size=4) +
coord_equal(ratio=1) + xlim(0, 10) + ylim(0, 10)

Resources