ggplot secondary axis wrong legend colours - r

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"))

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

No combining geom point with geom line in legend

I´m trying to get just one legend with shape that have the same color as the graph but it is just in black color:
type1 <-c("tmax","tmax","tmax","tmin","tmin","tmin","tmax","tmax","tmax","tmin","tmin","tmin")
station1 <-c("Anda","Anda","Anda","Anda","Anda","Anda","Mach","Mach","Mach","Mach","Mach","Mach")
date1 <-c(2001,2002,2003,2001,2002,2003,2002,2003,2004,2002,2003,2004)
meanTemp1<-c(15,16,15.5,5,7,8,13,14,12,9,9,7)
data11 <- data.frame(type1,station1,date1,meanTemp1)
plot1<- ggplot(data11, aes(x=date1, y=meanTemp1,group = station1,colour=station1,shape=station1)) +
geom_line () + guides(colour=FALSE)+
geom_point() +
xlab("year") + ylab("°C") +
labs(shape = "Station")+
facet_wrap(~type1,scales = "free")+
theme(axis.text.x = element_text(angle = 60,hjust = 1))
plot1
How can I get the legend fill with the same color as the graph instead of "black"?
As you rename shape legend in labs, you also need to rename colour legends using the same name in order they get merge.
Instead of using guides(colour = FALSE), you can pass in geom_line, the argument show.legend = FALSE to remove the colored lines in the legend:
plot1<- ggplot(data11, aes(x=date1, y=meanTemp1, group = station1,
colour=station1,
shape=station1)) +
geom_line (show.legend = FALSE) +
geom_point() +
xlab("year") + ylab("°C") +
labs(shape = "Station", colour = "Station")+
facet_wrap(~type1,scales = "free")+
theme(axis.text.x = element_text(angle = 60,hjust = 1))
plot1

Line plot legend does not appear

I am trying to plot a line plot in r by using ggplot. Unfortunately, the legend does not show up. Can anyone help me?
My code looks like the following:
dfdatavgsM=data.frame(datum, avgsätzegespMT, avgsätzegespML)
ggplot(data = dfdatavgsM, aes(x=datum, color=Wettbewerbsart))
+ geom_line(data=dfdatavgsM, aes(y = avgsätzegespML),color="red")
+ geom_line(data=dfdatavgsM, aes(y = avgsätzegespMT), color="blue")
+ geom_vline(xintercept=2011, size = 0.6)
+ scale_y_continuous(name="Anzahl an Sätzen")
+ scale_x_datetime(name = "Saison" ,date_breaks = ("2 year"),date_labels = "%Y")
+ ggtitle("Wettbewerbsintensität in Spielen mit |∆TTR| ≤ 118") + theme(panel.background = element_rect(fill = "white", colour = "black"))
+ theme(panel.grid.major = element_line(size = 0.25, linetype = 'solid', colour = "light grey")) + theme(axis.ticks = element_line(size = 1))
The legend will only appear if you use color inside an aes statement. You will need to reshape your data to 'long' format (e.g. with tidyr::gather), and have a single geom_line term and an aes including color=type. Something like this (not tested as I don't have your data)...
library(tidyverse)
dfdatavgsM=data.frame(datum, avgsätzegespMT, avgsätzegespML)
dfdatavgsMlong <- dfdatavgsM %>% gather(key = type, value = value, -datum)
ggplot(data = dfdatavgsMlong, aes(x=datum, y=value, color=type)) +
geom_line()

How to fix: when overlaying two scatter plots with using reorder of aes, the reorder gets lost

I have two scatter plots obtained from two sets of data that I would like to overlay, when using the ggplo2 for creating single plot i am using log scale and than ordering the numbers sothe scatter plot falls into kind if horizontal S shape. Byt when i want to overlay, the information about reordering gets lost, and the plot loses its shape.
this is how the df looks like (one has 1076 entries and the other 1448)
protein Light_Dark log10
AT1G01080 1.1744852 0.06984755
AT1G01090 1.0710359 0.02980403
AT1G01100 0.4716955 -0.32633823
AT1G01320 156.6594802 2.19495668
AT1G02500 0.6406005 -0.19341276
AT1G02560 1.3381804 0.12651467
AT1G03130 0.6361147 -0.19646458
AT1G03475 0.7529015 -0.12326181
AT1G03630 0.7646064 -0.11656207
AT1G03680 0.8340107 -0.07882836
this is for single plot:
p1 <- ggplot(ratio_log_ENR4, aes(x=reorder(protein, -log10), y=log10)) +
geom_point(size = 1) +
#coord_cartesian(xlim = c(0, 1000)) +
geom_hline(yintercept=0.1, col = "red") + #check gene
geom_hline(yintercept=-0.12, col = "red") +#check gene
labs(x = "Protein")+
theme_classic()+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())+
labs(y = "ratio Light_Dark log10")+
labs(x="Protein")
image=p1
ggsave(file="p1_ratio_data_ENR4_cys.svg", plot=image, width=10, height=8)
and for over lay:
p1_14a <- ggplot(ratio_log_ENR1, aes(x=reorder(protein, -log10), y=log10)) +
geom_point(size = 1) +
#coord_cartesian(xlim = c(0, 1000)) +
geom_hline(yintercept=0.1, col = "red") + #check gene
geom_hline(yintercept=-0.12, col = "red") +#check gene
labs(x = "Protein")+
theme_classic()+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())+
labs(y = "ratio Light_Dark log10")+
labs(x="Protein")+
geom_point()+
geom_point(data=ratio_log_ENR4, color="red")
p=ggplot(ratio_log_ENR1, aes(x=reorder(protein, -log10), y=log10)) +
geom_point(size = 1) +
#coord_cartesian(xlim = c(0, 1000)) +
geom_hline(yintercept=0.1, col = "red") + #check gene
geom_hline(yintercept=-0.12, col = "red") +#check gene
labs(x = "Protein")+
theme_classic()+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())+
labs(y = "ratio Light_Dark log10")+
labs(x="Protein")
p = p + geom_point(data=ratio_log_ENR4, aes(x=reorder(protein, -log10), y=log10), color ="red" )
p
I tried to change classes... but it cant be the problem since for single plot its working like it is
The easiest solution I see for you is just binding together your two dataframes before plotting.
a$color <- 'red'
b$color <- 'blue'
ab <- a %>%
rbind(b)
ggplot(ab, aes(x = fct_reorder(protein, -log10), y = log10, color = color)) +
geom_point() +
scale_color_identity()
You can find a nice cheat-sheet for working with factors here: https://stat545.com/block029_factors.html

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.

Resources