How to add a custom legend for geom_hline - r

Using the data below, notice the legend does not properly describe geom_hline:
df<-data.frame(
points=c(.153,.144,.126,.035, .037, .039, .010,.015,.07),
days=gl(3,1,9,labels=c("Sun","Mon","Tues")),
lang=c("en","en","en","pt","pt","pt","ko","ko","ko"))
ggplot(data=df[df$lang=="en",])+
geom_point(aes(x=days,y=points),size=5,colour='cyan',show_guide=F)+
geom_point(aes(x=days,y=points,colour=days),size=4,show_guide=F)+
facet_wrap(~lang,ncol=1,scales="free")+
xlab("")+
ylab("")+
scale_y_continuous(labels = percent_format())+
theme(legend.position="right",
legend.title = element_blank(),
strip.text.x = element_text(size = 13, colour = 'black', angle = 0),
axis.text.x=element_text(angle=0, hjust=.5, vjust=0),
legend.position = 'none',
panel.background = element_rect(fill = "#545454"),
panel.grid.major = element_line(colour = "#757575"),
panel.grid.minor = element_line(colour = "#757575"))+
geom_hline(yintercept=.136,color='cyan',size=2, show_guide=T)
Is there some way to create a custom legend that describes the geom_hline? [I'd like the legend to to have the name "Legend" with only one value labled "avg"]
Searching so, I found an example: ggplot legend showing transparency and fill color. They used scale_fill_manual, which I tried, but could not improve the legend displayed above.

It's a bit awkward, but this seems to work:
hline <- data.frame(yint = 0.136,lt = 'Avg')
ggplot(data=df[df$lang=="en",])+
geom_point(aes(x=days,y=points),size=5,colour='cyan')+
geom_point(aes(x=days,y=points,colour=days),size=4)+
facet_wrap(~lang,ncol=1,scales="free")+
xlab("")+
ylab("")+
scale_y_continuous(labels = percent_format())+
theme(legend.position="right",
legend.title = element_blank(),
strip.text.x = element_text(size = 13, colour = 'black', angle = 0),
axis.text.x=element_text(angle=0, hjust=.5, vjust=0),
legend.position = 'none',
panel.background = element_rect(fill = "#545454"),
panel.grid.major = element_line(colour = "#757575"),
panel.grid.minor = element_line(colour = "#757575"))+
geom_hline(data = hline,aes(yintercept=yint,linetype = lt),color = "cyan",size=2,show_guide = TRUE) +
scale_colour_discrete(guide = "none") +
scale_linetype_manual(name = 'Legend',values = 1,guide = "legend")
Ah, but you've included legend.title = element_blank() in there, which is why the legend is not named. Remove that to include the name.

Related

R color scatter plot with more color gradiant

Hello I have Dataframe ploting scatter plot with color using other column values plot is looking fine but the colour values are start from 0-100 and most of the values are in between 50-100 so I wanted put more color to diffrentiat can any one suggest me how can I do with the R, I tried with viridis color it is also looking same 50-100 color is almost looking similar color
link for the data
https://drive.google.com/file/d/1EKhRwup3vUC3KVFOOh4XtKERIr8FQj3x/view?usp=sharing
code what I tried
df=read.table("test.txt",sep='\t', header=TRUE)
df = data.frame(df)
p=ggplot(df, aes(log(data1), log(data2)),cex=1.9)+
geom_point(aes(color =data3)) +
theme(legend.position = "top")+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
theme(text = element_text(size = 20, face="bold"))
You can play with a customized color palette and scale_colour_gradientn like this:
library(RColorBrewer)
library(ggplot2)
#Data
df <- read.delim(file='test.txt',stringsAsFactors = F)
#Palette
myPalette <- colorRampPalette(rev(brewer.pal(11, "Spectral")))
sc <- scale_colour_gradientn(colours = myPalette(100))
#Plot
ggplot(df, aes(log(data1), log(data2)),cex=1.9)+
geom_point(aes(color =data3)) + sc +
theme(legend.position = "top")+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
theme(text = element_text(size = 20, face="bold"))
Output:
If you want more color try this:
#Palette 2
sc2 <- scale_colour_gradientn(colours = rainbow(7))
#Plot
ggplot(df, aes(log(data1), log(data2)),cex=1.9)+
geom_point(aes(color =data3)) + sc2 +
theme(legend.position = "top")+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
theme(text = element_text(size = 20, face="bold"))
Output:
Update2: With breaks you can define limits for the color scale:
#Plot 3
ggplot(df, aes(log(data1), log(data2),color=data3),cex=1.9)+
geom_point() +
scale_colour_gradientn(colours = rainbow(25),breaks = seq(0,100,by=5))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
theme(text = element_text(size = 12, face="bold"),
legend.text = element_text(size = 7, face="bold"))
Output:
Update 3: If you want to have different colors you can mix different palettes like this:
#Plot
ggplot(df, aes(log(data1), log(data2),color=data3),cex=1.9)+
geom_point() +
scale_colour_gradientn(colours = c(viridis::inferno(5),
viridis::plasma(5),
viridis::magma(5),
viridis::viridis(5),
rainbow(5)),breaks = seq(0,100,by=5))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line = element_line(colour = "black"))+
theme(text = element_text(size = 12, face="bold"),
legend.text = element_text(size = 7, face="bold"))
Output:

Unable to change color of line and scatter plot R ggplot

I am relatively new to ggplot plot so I think some of the intricacies are lost on me. I have plotted multiple months of data where the data is binned by the hour. Each line is meant to be colored by month where the x-axis is the hour of the day. I am having trouble changing the color of the lines and moved things around in ggplot to try to get it to work but the color of all lines remain black"
Here is an example of some of the data I am plotting: Example data
Here is my code:
p <- ggplot(mtozoneavgk_month, aes(hour, Avgk, group = factor(Date) )) +
geom_point(size = 4) +
geom_line(size = 1)+
scale_color_manual(values = c("#DC143C", "#B22222", "#000080", "#00008B",
"#0000CD", "#0000FF", "#66B2FF", "#FF6347", "#FF0000", "#B22222"),
name = "Month", labels = c("Sept-2019", "Oct-2019", "Nov-2019", "Dec-2019",
"Jan-2020", "Feb-2020", "Mar-2020", "April-2020", "May-2020", "Jun-2020"),
expand = c(0, 0))+
ylab("rate constant (k)")+
scale_y_continuous(label=scientific_10)+
#scale_y_continuous(labels = fancy_scientific)+
theme(axis.ticks.length = unit(0.2, "cm"),
axis.ticks = element_line(size = 2),
axis.text=element_text(size=12, face = 'bold'),
axis.title=element_text(size=14,face="bold"),
axis.text.x = element_text(color = "black", face = "bold", size = 14),
axis.text.y = element_text(color = "black", size = 14),
legend.title=element_text(size=14, face = "bold"),
legend.text = element_text(size = 14, face = "bold"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA, size=3))
p + scale_x_continuous(breaks = c(0,2,4,6,8,10,12,14,16,18,20,22,24),
label = c(0,2,4,6,8,10,12,14,16,18,20,22,24),
expand = c(0, 0))
Any help would be appreciated!
If we simplify your code as follows (letting ggplot2 to take care of colors and labels):
p <- ggplot(mtozoneavgk_month, aes(hour, Avgk, group = factor(Date), color = factor(Date))) +
geom_point(size = 4) +
geom_line(size = 1)+
ylab("rate constant (k)")+
theme(axis.ticks.length = unit(0.2, "cm"),
axis.ticks = element_line(size = 2),
axis.text=element_text(size=12, face = 'bold'),
axis.title=element_text(size=14,face="bold"),
axis.text.x = element_text(color = "black", face = "bold", size = 14),
axis.text.y = element_text(color = "black", size = 14),
legend.title=element_text(size=14, face = "bold"),
legend.text = element_text(size = 14, face = "bold"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA, size=3))
We obtain the following plot:
If you also want to control colors I would suggest to use named vectors:
pcolor <- c("#DC143C", "#B22222", "#000080", "#00008B",
"#0000CD", "#0000FF", "#66B2FF", "#FF6347", "#FF0000")
names(pcolor) <- unique(mtozoneavgk_month$Date)
plabel <- c("Sept-2019", "Oct-2019", "Nov-2019",
"Jan-2020", "Feb-2020", "Mar-2020", "April-2020", "May-2020", "Jun-2020")
names(plabel) <- unique(mtozoneavgk_month$Date)
p <- ggplot(mtozoneavgk_month, aes(hour, Avgk, group = factor(Date), color = factor(Date))) +
geom_point(size = 4) +
geom_line(size = 1)+
scale_color_manual(values = pcolor,
name = "Month",
labels = plabel,
expand = c(0, 0))+
ylab("rate constant (k)")+
theme(axis.ticks.length = unit(0.2, "cm"),
axis.ticks = element_line(size = 2),
axis.text=element_text(size=12, face = 'bold'),
axis.title=element_text(size=14,face="bold"),
axis.text.x = element_text(color = "black", face = "bold", size = 14),
axis.text.y = element_text(color = "black", size = 14),
legend.title=element_text(size=14, face = "bold"),
legend.text = element_text(size = 14, face = "bold"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA, size=3))
Which results in:
Remark: I do not know if it was because of the sample you gave us but December 2019 is missing so tweaked a little bit your code. Be aware of it when you make your own

Use Linetypes and colors examples as axis label in ggplot2

I have a graph with four lines with two different linetypes (solid and dashed) and two colors. I want to display a table below the graph containing some information about each curve, e.g. :
The labels of the y-axis of this table are "S.2", "D.2",...
Is it possible to use labels (for the y-axis) that are examples of what the curve looks like instead of text?
Such as in the legend of the graph?
That is instead of "S.2" having a short blue dashed line?
Here is the code to produce the plot
require(ggplot2)
require(grid)
require(gtable)
## graph
g1<-ggplot() + aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="1",linetype="S") + geom_line()+
geom_line(aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="1",linetype="D"))+
geom_line(aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="2",linetype="S"))+
geom_line(aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="2",linetype="D"))+
scale_colour_manual(breaks=c("1","2"),values=c("#cd7118","#1874cd"))+
scale_x_continuous(limits = c(0,5),breaks = 0:5,expand=c(0,0))+
scale_linetype_manual(breaks=c("S","D"),values=c("solid","dashed"))+
theme(
axis.line = element_line(size = 0.2, linetype = 'solid',colour = "black"),
axis.text = element_text(size=10),
axis.title = element_blank(),
legend.title = element_blank(),
legend.background = element_blank(),
legend.key = element_blank(),
legend.position = c(.1,.5)
)
## table
count<-data.frame(time=rep(0:5,4),count=rep(0:5,4),col=c(rep("1",12),rep("2",12)),lintype=rep(c(rep("S",6),rep("D",6)),2))
g2<-ggplot(count, aes(x = time , y = interaction(factor(lintype),factor(col)), colour=factor(col), label=count)) +
geom_text(size=4) +
scale_colour_manual(breaks=c("1","2"),values=c("#cd7118","#1874cd"))+
scale_x_continuous(limits = c(0,5),breaks = 0:5,expand=c(0,0))+
theme(
legend.position = "none",
panel.background = element_rect(fill = "white",colour = "white",size = 0.5, linetype = "solid"),
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_text(size=10, color = 'black',margin = margin(t = 0, r = 20, b = 0, l = 0)),
axis.ticks=element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.title = element_text(size=10),
plot.margin = margin(t=1,b=1,r=15,l=10,unit="pt")
)
#
merge = rbind(ggplotGrob(g1), ggplotGrob(g2), size="last")
panels <- merge$layout$t[grep("panel", merge$layout$name)]
merge$heights[panels[1]] <- unit(10,"cm")
merge$heights[panels[2]]<-unit(6,"lines")
merge <- gtable_add_rows(merge, heights = unit(1,"line"), 1)
merge$layout$clip[merge$layout$name=="panel"]<-"off"
grid.draw(merge)

Conditional argument in ggplot custom theme

I am developing a custom theme based on the 538 theme in ggthemes. I have a particular use case where I would like to conditionally change the legend text if I am preparing graphs about organisms. I want to make the legend text italics if I am reporting Genus species results.
Here is my theme so far:
theme_EPI <- function() {
theme_fivethirtyeight(base_size = 14) %+replace%
theme(
panel.background = element_blank(),
plot.background = element_rect(fill = 'white', colour = NA),
plot.title = element_text(size = 18),
strip.text = element_text(size=14),
legend.text = element_text(size = 12, face = 'italic'),
legend.background = element_rect(fill="transparent", colour=NA),
legend.key = element_rect(fill="transparent", colour=NA),
panel.grid.major.y = element_line(colour = 'grey90'),
panel.grid.major.x = element_blank(),
strip.background = element_blank()
)
}
If have tried passing the parameter organism=TRUE to the the function call and then an ifelse(organism==TRUE, face='italic', 'face='plain') in the element_text.
Is this even possible in a custom theme?
Yes, this is definitely possible, you just have to slightly rethink how the ifelse() will work:
theme_EPI = function(organism = TRUE) {
theme_dark() %+replace%
# axis.title: labels for x and y axes
theme(axis.title = element_text(
face = ifelse(organism, 'italic', 'plain')
))
}
ggplot(iris, aes(Petal.Width, Petal.Length)) +
geom_point() +
theme_EPI() # Default: organism = TRUE
ggplot(iris, aes(Petal.Width, Petal.Length)) +
geom_point() +
theme_EPI(organism = FALSE)

The mirror_ticks function not working for ggplot

I want to place ticks on all four sides of my graph. The way suggested for this is mirror_ticks.
library(ggplot2)
library(ggplotTicks)
sp6<-ggplot(Anna_Smooth, aes(y=log10(Prob2), x=log10(AvSize)))+
geom_point( data=Anna_Smooth, aes(y=log10(Prob2), x=log10(AvSize), color=PART) )+
guides( color=FALSE)
sp8<-sp6+ labs(x=expression(paste(log(s))))+
labs(y=expression(paste(log(P(s)))) )+
theme(axis.text.y = element_text(size=14),
axis.text.x = element_text(size=14),
axis.title.y = element_text(size=15),
axis.title.x = element_text(size=15),
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
panel.border = element_rect(colour = "black", fill=NA, size=2)
)
sp10<-mirror_ticks(sp10, allPanels=TRUE)
My output sp10 has no ticks on opposite panels, same result if I put allPanels=TRUE
Is there a fix? I am open to learn how one does this with theme settings?
As of ggplot2 version 2.2.0 (2016-11-11), the scale_x_continuous() and scale_y_continuous() can display a secondary axis which is positioned opposite to the primary axis and which can be controlled with the sec.axis argument.
This can be used to mirror the tick marks.
The OP hasn't provided reproducible data so we use the mpg dataset which comes with the ggplot2 package:
Chart without mirrored tick marks
library(ggplot2)
g1 <- ggplot(mpg, aes(log10(displ), log10(hwy))) +
geom_point() +
theme(
axis.text.y = element_text(size = 14),
axis.text.x = element_text(size = 14),
axis.title.y = element_text(size = 15),
axis.title.x = element_text(size = 15),
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
panel.border = element_rect(
colour = "black",
fill = NA,
size = 2
)
)
g1
Chart with secondary axes
g1 +
scale_x_continuous(sec.axis = dup_axis()) +
scale_y_continuous(sec.axis = dup_axis())
g1 +
scale_x_continuous(sec.axis = dup_axis(name = NULL)) +
scale_y_continuous(sec.axis = dup_axis(name = NULL))
g1 +
scale_x_continuous(sec.axis = dup_axis(name = NULL, labels = NULL)) +
scale_y_continuous(sec.axis = dup_axis(name = NULL, labels = NULL))
Mirrored tick marks with log10 scales
The secondary axes are also available with the scale_x_log10() and scale_x_log10() functions.
So, it can be avoided to use the log() function within the call to aes() but by specifying an appropriate log scale:
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
theme(
axis.text.y = element_text(size = 14),
axis.text.x = element_text(size = 14),
axis.title.y = element_text(size = 15),
axis.title.x = element_text(size = 15),
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black"),
panel.border = element_rect(
colour = "black",
fill = NA,
size = 2
)
) +
scale_x_log10(sec.axis = dup_axis(name = NULL, labels = NULL)) +
scale_y_log10(sec.axis = dup_axis(name = NULL, labels = NULL))

Resources