Legend doesn't go to the bottom - r

I've copy a code of another user and am adapting it to my data.
The code:
library(gridExtra)
library(grid)
library(ggplot2)
x <- data.frame(
date = seq(as.Date("2012-01-01"),as.Date("2012-12-31"), by="week"),
rain = sample(0:20,53,replace=T),
flow1 = sample(50:150,53,replace=T),
flow = sample(50:200,53,replace=T))
g.top <- ggplot(x, aes(x = date, y = rain, ymin=0, ymax=rain)) +
geom_linerange() +
scale_y_continuous(limits=c(22,0),expand=c(0,0), trans="reverse")+
theme_classic() +
theme(plot.margin = unit(c(5,5,-32,6),units="points"),
axis.title.y = element_text(vjust = 0.3))+
labs(y = "Rain (mm)")
g.bottom <- ggplot(x, aes(x = date)) +
geom_line(aes(y = flow, colour = "flow")) +
geom_line(aes(y = flow1, colour = "flow1")) +
theme(legend.position="bottom") +
theme_classic() +
theme(plot.margin = unit(c(0,5,1,1),units="points")) +
labs(x = "Date", y = "River flow (m/s)")
grid.arrange(g.top, g.bottom , heights = c(1/5, 4/5))
I wanted that the legend went to the bottom, but it doesn't go.
enter image description here

try this:
library(gridExtra)
library(grid)
library(ggplot2)
x <- data.frame(
date = seq(as.Date("2012-01-01"),as.Date("2012-12-31"), by="week"),
rain = sample(0:20,53,replace=T),
flow1 = sample(50:150,53,replace=T),
flow = sample(50:200,53,replace=T))
g.top <- ggplot(x, aes(x = date, y = rain, ymin=0, ymax=rain)) +
geom_linerange() +
scale_y_continuous(limits=c(22,0),expand=c(0,0), trans="reverse")+
theme_classic() +
theme(plot.margin = unit(c(5,5,-32,6),units="points"),
axis.title.y = element_text(vjust = 0.3))+
labs(y = "Rain (mm)")
g.bottom <- ggplot(x, aes(x = date)) +
geom_line(aes(y = flow, colour = "flow")) +
geom_line(aes(y = flow1, colour = "flow1")) +
theme_classic() +
# here the mod
theme(plot.margin = unit(c(0,5,1,1),units="points"),legend.position="bottom") +
labs(x = "Date", y = "River flow (m/s)")
grid.arrange(g.top, g.bottom , heights = c(1/5, 4/5))

Related

Color for facet grid, based on x-axis, in ggplot2

I have color for each variable (fishing strategy), however, if I put it in a facet grid like this, based on the years, I can't set up the colors accordingly. I want to have one color for each fishing strategy instead of one color for each year, but also need the legend for fishing strategies with color or just years without color. But I didn't manage to do that. Can someone help me with this?
With this code:
spaclu <- ggplot(io1, aes(y= effort, x=factor(clu_name2), fill= factor(year))) + geom_bar(stat="identity", position="dodge")
+ theme_minimal()
spaclu + facet_grid(vessel_category~geartype_clu2, scales = "free")
+ labs(fill = "Year", x = "Fishing strategies", y = "Total REA", title = "Based on the REA")
+ theme(text = element_text(size = 13))
+ theme(legend.position = "bottom")
+ theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
+
scale_fill_manual(values = c("GIL_COD" = "#004c6d",
"GIL_FRS" = "#00ffff",
"GIL_FLE" = "#00a1c1",
"GIL_HER" = "#00cfe3",
"PAS_FLA" = "#78ab63",
"POL_FRS" = "#6efa75",
"BST_MIX" = "#ffc334",
"MPT_HER" = "#ff9509",
"BPT_HER" = "#ffb6de",
"BPT_COD" = "#cc0089"))
I get this
but if I removed the scale fill manual part, it looked like this
I think I've worked it out, but I don't have your data. (It's a bit messy.)
I used the dataset diamonds and renamed the fields. The first plot is supposed to represent your second plot, where you have removed the scale_color_manual.
The data first:
library(tidyverse)
# create variables
io1 <- diamonds %>%
mutate(year = cut,
effort = x,
clu_name2 = color,
vessel_category = rep(c("Passive","Active"), nrow(diamonds)/2),
geartype_clu2 = rep(LETTERS[1:3], nrow(diamonds)/3))
levels(io1$year) <- c(2019:2023)
Original plot as you've coded:
# grid faceting/color
spaclu <- ggplot(io1, aes(y= effort, x=factor(clu_name2), fill= factor(year))) +
geom_col(position = "dodge") +
theme_minimal()
spaclu + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "Year", x = "Fishing strategies", y = "Total REA",
title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
The primary differences are the arguments group = year and fill = clu_name2.
p2 <- ggplot(io1, aes(x = clu_name2, y = effort, group = year, fill = clu_name2)) +
geom_col(position = "dodge") +
theme_minimal()
p2 + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "", x = "Fishing strategies\ngrouped by years",
y = "Total REA", title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
Keep in mind the legend here is fishing strategies. If you want the years shown, perhaps a second depth label with scale_fill_manual() would be a good approach.
Now as far getting the years and the strategies in the legend or as legends. You may be better off with adding a second scale axis and using the first version. This can be done with the package ggnewscale. You'll have to adjust the font size or expand or add to the margin, though.
# grid faceting/color
spaclu <- ggplot(io1, aes(y= effort, x=factor(clu_name2), fill= factor(year),
group = year)) +
geom_col(position = "dodge") +
theme_minimal()
spaclu + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "Year", x = "Fishing strategies", y = "Total REA",
title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
ggnewscale::new_scale("fill") + # added scale here
geom_tile(aes(fill = clu_name2, y = 1)) +
scale_fill_discrete(name = "Strategies")
It doesn't quite work out when using it with the second option
p2 <- ggplot(io1, aes(x = clu_name2, y = effort, group = year, fill = clu_name2)) +
geom_col(position = "dodge") +
theme_minimal()
p2 + facet_grid(vessel_category~geartype_clu2, scales = "free") +
labs(fill = "", x = "Fishing strategies\ngrouped by years",
y = "Total REA", title = "Based on the REA") +
theme(text = element_text(size = 13)) +
theme(legend.position = "bottom") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
scale_fill_manual(values = c("D" = "#004c6d",
"E" = "#00ffff",
"F" = "#00a1c1",
"G" = "#00cfe3",
"H" = "#78ab63",
"I" = "#6efa75",
"J" = "#ffc334",
"K" = "#ff9509",
"L" = "#ffb6de",
"M" = "#cc0089")) +
ggnewscale::new_scale("fill") +
geom_tile(aes(fill = year, y = 1)) +
scale_fill_viridis_d(name = "Years")

Why is the themes function not applying changes to the ggplot?

I want to change the text size of my y axis descrption and center my plottitle.
Everything coded within the themes function is not being applied to my graph.
Where is the problem?
finalchart = ggplot(euall,
aes(day, cumulative_cases_of_14_days_per_100000 ,
group = countriesAndTerritories)) +
geom_bar(stat = "identity" ,
col = "white" ,
fill = "darkred") +
facet_wrap("countriesAndTerritories") +
geom_line(aes(y = rollmean(cumulative_cases_of_14_days_per_100000, 1,
na.pad = TRUE),
col = "pink"),
show.legend = FALSE) +
labs(title = "COVID infections in the European Union in September 2020" ,
x = "\nSeptember" ,
y = "Infections per 100'000\n" ,
caption = "source: https://opendata.ecdc.europa.eu/covid19/casedistribution/csv") +
theme(axis.text.y = element_text(size = 5) ,
axis.title.y = element_text(size = 10) ,
plot.title = element_text(hjust = 0.5)) +
theme_minimal()
finalchart
The problem is the order in which you call theme() and theme_minimal(). By calling theme_minimal() second your manual settings in theme() are overwritten.
library(ggplot2)
library(patchwork)
p1 <- ggplot(data = cars, aes(x = speed, y = dist)) +
geom_point() +
ggtitle("theme_minimal second") +
theme(title = element_text(size = 24, color = "red", face = "bold")) +
theme_minimal()
p2 <- ggplot(data = cars, aes(x = speed, y = dist)) +
geom_point() +
ggtitle("theme_minimal first") +
theme_minimal() +
theme(title = element_text(size = 24, color = "red", face = "bold"))
p1+p2

How to put the y axis label over 2 lines ggplot

I am trying to make the y axis of the second plot over 2 lines. Using '\n' for the first plot worked fine but using it on the second makes the text in odd places (maybe because of the italics).
p1 <- ggplot(data = new_data) +
geom_line(mapping = aes(x = Date,
y = Proportion,
group = Species,
colour = Species)) +
scale_colour_manual(values=c(Golden_Trevally="goldenrod2",
Red_Snapper="firebrick2",
Sharksucker_Remora="darkolivegreen3",
Juvenile_Remora="aquamarine2")) +
xlab("Date (2014-2018)") +
ylab("Total Presence \n Per Month ") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) +
theme(legend.position="top") +
labs(colour = "Hitchhiker Species")
new_data_counts <- new_data %>% select(Date, Count)
new_data_counts <- new_data_counts[!duplicated(new_data_counts),]
p2 <- ggplot(data = new_data_counts) +
geom_bar(mapping = aes(x = Date, y = Count), stat = 'identity') +
xlab("Date (2014-2018)") +
ylab("Total Number of "~italic(\nM.alfredi)~" Encounters") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
grid.arrange(p1,p2)
You can try this:
geom_line(mapping = aes(x = Date,
y = Proportion,
group = Species,
colour = Species)) +
scale_colour_manual(values=c(Golden_Trevally="goldenrod2",
Red_Snapper="firebrick2",
Sharksucker_Remora="darkolivegreen3",
Juvenile_Remora="aquamarine2")) +
xlab("Date (2014-2018)") +
ylab("Total Presence \n Per Month ") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) +
theme(legend.position="top") +
labs(colour = "Hitchhiker Species")
new_data_counts <- new_data %>% select(Date, Count)
new_data_counts <- new_data_counts[!duplicated(new_data_counts),]
p2 <- ggplot(data = new_data_counts) +
geom_bar(mapping = aes(x = Date, y = Count), stat = 'identity') +
labs(x="Date (2014-2018)",
y=expression(atop(paste("Total Number of"), paste(italic("M.alfredi"), " Encounters")))) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
grid.arrange(p1,p2)
You need space between \n and M.alfredi in p2. Since there is no reproducible example, here is my suggestion for the second plot,
p2 <- ggplot(data = new_data_counts) +
geom_bar(mapping = aes(x = Date, y = Count), stat = 'identity') +
xlab("Date (2014-2018)") +
ylab("Total Number of "~italic(\n M.alfredi)~" Encounters") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
It should solve your problem.

remove axis.ticks from some panels in facet_wrap

I am using ggplot to plot y versus x for two factors f1 and f2 using the facet_wrap. I want to keep the ticks for the y axis only for the first column (representing given value of factor f2) and remove the others. Is there away to do this? I tried many ways (including scale = free_y) but no success. Below is a simple code:
y = rnorm(100)
x = rnorm(100)
type = rep(1:5,20)
f1 = sample(LETTERS[1:3], 100, replace=TRUE, prob=c(0.3, 0.3, 0.4) )
f2 = sample(LETTERS[4:6], 100, replace=TRUE, prob=c(0.3, 0.3, 0.4) )
df = data.frame(cbind(x, y,f1,f2, type))
df$x = as.numeric(as.character(df$x)); df$y = as.numeric(as.character(df$y))
p1 = ggplot(data = df, aes(x, y, linetype = type)) +
geom_line(aes(linetype = type))+ scale_linetype_manual(values=c("solid", "F1", "dotted", "twodash","dashed")) +
scale_size_manual(values=c(0.5, 0.5, 0.5,0.5,0.5)) +
geom_point(size=0.5, shape=21, fill="black") +
labs(y="y") +
facet_wrap( ~ f1 + f2 , ncol=3, scales = "free_y") +
theme_bw() +
theme(panel.margin = unit(0.8, "lines")) +
theme(plot.title = element_text(size = rel(1.2))) +
theme(axis.ticks.length=unit(0.2,"cm")) +
theme(strip.text.x = element_text(size=11)) +
theme(strip.background = element_rect(colour="white", fill="gray"))
p1
Questions:
How to keep the ticks for the y axis only for the first column in the left (i.e factor f2 = "D"). I know the y axis have different levels but this is not an issue for me.
many thanks
Abderrahim
I think you are actually after facet_grid as opposed to facet_wrap.
See the below:
p1 <- ggplot(data = df, aes(x, y, linetype = type)) +
geom_line(aes(linetype = type))+ scale_linetype_manual(values=c("solid", "F1", "dotted", "twodash","dashed")) +
scale_size_manual(values=c(0.5, 0.5, 0.5,0.5,0.5)) +
geom_point(size=0.5, shape=21, fill="black") +
labs(y="y") +
facet_grid( f1~f2 ) +
theme_bw() +
theme(panel.margin = unit(0.8, "lines")) +
theme(plot.title = element_text(size = rel(1.2))) +
theme(axis.ticks.length=unit(0.2,"cm")) +
theme(strip.text.x = element_text(size=11)) +
theme(strip.background = element_rect(colour="white", fill="gray"))
p1

Pie plot getting its text on top of each other

Just trying to fix this overlapped labeling:
My code:
values=c(164241,179670)
labels=c("Private", "Public")
colors=c("#cccccc", "#aaaaaa")
categoriesName="Access"
percent_str <- paste(round(graph$values / sum(graph$values) * 100,1), "%", sep="")
values <- data.frame(val = graph$values, Type = graph$labels, percent=percent_str )
pie <- ggplot(values, aes(x = "", y = val, fill = Type)) + geom_bar(width = 1) +
geom_text(aes(y = **val + 1**, **hjust=0.5**, **vjust=-0.5**, label = percent), colour="#333333", face="bold", size=10) +
coord_polar(theta = "y") + ylab(NULL) + xlab(NULL) +
scale_fill_manual(values = graph$colors) + labs(fill = graph$categoriesName) +
opts( title = graph$title,
axis.text.x = NULL,
plot.margin = unit(c(0,0,0,0), "lines"),
plot.title = theme_text(face="bold", size=14),
panel.background = theme_rect(fill = "white", colour = NA) )
print(pie)
Tried messing with the values marked with asterisks (** **) but haven't got anywhere.
Any help appreciated.
here is an example:
pie <- ggplot(values, aes(x = "", y = val, fill = Type)) +
geom_bar(width = 1) +
geom_text(aes(y = val/2 + c(0, cumsum(val)[-length(val)]), label = percent), size=10)
pie + coord_polar(theta = "y")
Perhaps this will help you understand how it work:
pie + coord_polar(theta = "y") +
geom_text(aes(y = seq(1, sum(values$val), length = 10), label = letters[1:10]))

Resources