r adding line (new coordinates) to ggplot2 scaterplot - r

How can I add a line with new x coordinates to my scatterplot? I get an error saying the line x-values must match those from my scatterplot.. I tried using geom_line() as you can see
library(ggplot2)
x <- c(1,2,3)
y <- c(4,5,6)
a <- seq(0.5,5, by = 0.5)
b <- seq(1,10)
ggplot(as.data.frame(cbind(x,y)), aes(x, y)) +
geom_point(shape = 1) +
geom_point(aes(2.5,2.5, colour = "My Portfolio"),
shape = 18,
size = 3) +
geom_line(aes(a, b)) +
ggtitle("Efficient Frontier") +
xlab("Volatility (Weekly)") +
ylab("Expected Returns (Weekly)") +
theme(plot.title = element_text(size=14, face="bold.italic", hjust = 0.5, margin=margin(0,0,15,0)),
axis.title.x = element_text(size = 10, margin=margin(15,0,0,0)),
axis.title.y = element_text(size = 10, margin=margin(0,15,0,0)),
panel.border = element_rect(colour = "black", fill=NA, size=1),
legend.position = c(0.93,0.06),
legend.title = element_blank(),
legend.text = element_text(size=8),
legend.background = element_rect(color = "black"),
legend.key=element_blank())
thanks!

You have to provide a new data.frame to geom_line() and set the aestetics accordingly.
library(ggplot2)
x <- c(1,2,3); y <- c(4,5,6)
a <- seq(0.5,5, by = 0.5); b <- seq(1,10)
ggplot(as.data.frame(cbind(x,y)), aes(x, y)) +
geom_point(shape = 1) +
geom_point(aes(2.5,2.5, colour = "My Portfolio"),
shape = 18,
size = 3) +
geom_line(data=data.frame(a,b), mapping=aes(x=a, y=b)) +
ggtitle("Efficient Frontier") +
xlab("Volatility (Weekly)") +
ylab("Expected Returns (Weekly)") +
theme(plot.title = element_text(size=14, face="bold.italic", hjust = 0.5, margin=margin(0,0,15,0)),
axis.title.x = element_text(size = 10, margin=margin(15,0,0,0)),
axis.title.y = element_text(size = 10, margin=margin(0,15,0,0)),
panel.border = element_rect(colour = "black", fill=NA, size=1),
legend.position = c(0.93,0.06),
legend.title = element_blank(),
legend.text = element_text(size=8),
legend.background = element_rect(color = "black"),
legend.key=element_blank())

Related

geom_point not showing up on ggplot with geom_sf of rivers

I am trying to build a map that contains a few points overlayed onto rivers. I am using code adapted from https://milospopovic.net/map-rivers-with-sf-and-ggplot2-in-r/, but I downloaded the North America map and substituted
st_polygon(list(cbind(
c(-84.9, -84.9, -84.0, -84.0, -84.9),
c(34.4, 35.05, 35.05, 34.4, 34.4)
))),
crs = crsLONGLAT)
to create my bounding box.
test.point <- data.frame("x"= -84.73405, "y"= 35.00988)
p <-
ggplot()+
geom_point(data= test.point, aes(x=x, y=y), color= "black", fill= "black") +
geom_sf(data=na_riv, aes(color=factor(ORD_FLOW), size=width)) +
coord_sf(crs = 4087,
xlim = c(bbox["xmin"], bbox["xmax"]),
ylim = c(bbox["ymin"], bbox["ymax"])) +
labs(x= "", subtitle="",
title="Rivers of the Southeast",
caption="©2022\nSource: ©World Wildlife Fund, Inc. (2006-2013)\n HydroSHEDS database http://www.hydrosheds.org") +
scale_color_manual(
name = "",
values = c('#081f6b', '#08306b', '#08519c', '#2171b5', '#4292c6', '#6baed6', '#9ecae1', '#c6dbef', '#deebf7')) +
scale_size(range=c(0, .3)) +
scale_alpha_manual(values=c("2"= 1, "3" = 1, "4" = 1, "5" = .7, "6" = .6, "7" = .4, "8" = .3, "9" = .2, "10" = .1)) +
theme_bw() +
theme(text = element_text(family = "georg"),
panel.background = element_blank(),
legend.background = element_blank(),
legend.position = "none",
panel.border = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
plot.title = element_text(size=40, color="#2171b5", hjust=0.5, vjust=0),
plot.subtitle = element_text(size=14, color="#ac63a0", hjust=0.5, vjust=0),
plot.caption = element_text(size=10, color="grey60", hjust=0.5, vjust=10),
legend.text = element_text(size=9, color="grey20"),
legend.title = element_text(size=10, color="grey20"),
strip.text = element_text(size=12),
plot.margin = unit(c(t=1, r=0, b=-1, l=-1),"lines"))
p
The above code yields a pretty map of all of the rivers but the point doesn't show up. :(
Here is one way to get around this. Basically you can convert the points you want to highlight a a simple feature geometry:
test.point <- data.frame(x = c(-84.73405, -84.6), y = c(35.00988, 34.6))
new_test.point <- st_sfc(st_multipoint(as.matrix(test.point)), crs = crsLONGLAT)
Then, I just filtered the data to have only the rivers present in the area of interested:
nariv = nariv %>% mutate(inter = as.integer(st_intersects(geometry, bbox)))
nariv_filt = nariv %>% filter(!is.na(inter))
And create the plot:
ggplot() +
geom_sf(data = nariv_filt, aes(color = factor(ORD_FLOW), size = width, alpha = width)) +
geom_sf(data = new_test.point, color="red", size=5)+
coord_sf(crs = prj, xlim = c(bb["xmin"], bb["xmax"]),ylim = c(bb["ymin"], bb["ymax"])) +
geom_point(data = test.point, aes(x=x, y=y), color="red", size=5)+
labs(y = "", subtitle = "", x = "", title = "Rivers of North and Central America") +
scale_color_manual(name = "",
values = c(
"#08306b", "#1c4680", "#305d94", "#4574a7",
"#5d8cb9", "#77a4cb", "#deebf7", "#deebf7", "#deebf7"
), drop = F) +
scale_alpha(range = c(0.3, 0.8)) +
scale_size(range = c(0, 3)) +
theme_minimal() +
theme(
text = element_text(family = "Montserrat"),
panel.background = element_blank(),
legend.background = element_blank(),
legend.position = "none",
panel.border = element_blank(),
#panel.grid.minor = element_blank(),
#panel.grid.major = element_blank(),
#plot.title = element_text(size = 100, color = "#2171b5", hjust = 0.5, vjust = -22),
#plot.subtitle = element_text(size = 14, color = "#ac63a0", hjust = 0.5, vjust = 0),
#plot.caption = element_text(size = 40, color = "grey60", hjust = 0.5, vjust = 120),
#axis.title.x = element_text(size = 10, color = "grey20", hjust = 0.5, vjust = -6),
legend.text = element_text(size = 9, color = "grey20"),
legend.title = element_text(size = 10, color = "grey20"),
strip.text = element_text(size = 12),
#plot.margin = unit(c(t = -2.5, r = -10, b = -10, l = -10), "lines"),
axis.title.y = element_blank(),
axis.ticks = element_blank(),
#axis.text.x = element_blank(),
#axis.text.y = element_blank()
)

Make R Plot Axes the Same for Multi-Plot Figure

I have 3 multi-plot figures I'm making for a manuscript and R is shrinking the first plot in the 2 figures with 3 paneled plots. They have different axes and scales so I couldn't use a facet function, but ggarrange() does what I need. Is there a way to make the size of the actual graphs identical?enter image description here
Plot 1 axes smaller
Here's the script generating them:
library(ggplot2)
library(ggpubr)
library(ggpmisc)
library(ggrepel)
library(tidyverse)
summary_bp <- read.table("1500bp_amas_summary.txt", header=TRUE)
alignment_length <- summary_bp$Alignment_length
no_inf_sites <- summary_bp$Parsimony_informative_sites
Length_Site_Reg <- ggplot(summary_bp, aes(x=alignment_length, y=no_inf_sites)) +
geom_point(shape = 1, size = 1) +
geom_smooth(method = lm, size = 0.7) +
stat_regline_equation(label.x = 3000, label.y = 3500, geom = "text", aes(label= ..rr.label..), size = 2) +
stat_cor(method = "pearson", label.x = 3000, label.y = 3100,aes(label = ..p.label..), size = 2) +
coord_cartesian(xlim = c(1500, 15000), ylim = c(0,4000)) +
scale_x_continuous(breaks = seq(1500, 15000, by=1500)) +
scale_y_continuous(breaks = seq(0, 4000, by=500)) +
labs( x = "Alignment Lengths", y = "Number of Parsimony \n Informative Sites") +
theme(aspect.ratio = 1, axis.text.x = element_text(angle=45, hjust = 1),
axis.line = element_line(color = "black"), panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text = element_text(size = 7),
axis.title.x = element_text(size = 9, face = "bold"), axis.title.y = element_text(size = 8, face = "bold"))
Length_Site_Reg
#Fig. 3b) GC hist
summary_all <- read.table("summary_trim.txt", header=TRUE, sep = ",")
GC_hist <- ggplot(data = summary_all, aes(x=GC_content)) +
geom_histogram(binwidth = 0.025, fill = "white", color = "black") +
xlim(0.3,0.725) +
coord_cartesian( ylim = c(0,1050)) +
labs(x = "GC Content", y = "Number of Orthologs") +
theme(aspect.ratio = 1, panel.background = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), legend.position = c(0.75, 0.65),
axis.line = element_line(color = "black"), axis.text = element_text(size = 8),
axis.title = element_text(size = 9, face = "bold"), legend.key.size = unit(0.4, 'cm'),
legend.key.height = unit(0.4, 'cm'),
legend.key.width = unit(0.4, 'cm'),
legend.title = element_text(size=6),
legend.text = element_text(size=6)) +
geom_vline(aes(xintercept=mean(GC_content), color="mean"),
linetype="solid", size=0.5, show.legend = FALSE)
GC_hist
# Fig. 3c) K2P Divergence Hist
#trimmed_k2 <- file.choose()
trimmed_k2_data <- read.table("trimmed_alignment_k2.csv", header=TRUE, sep = ",")
trimmed_k2_data
trimmed_k2_data_hist <- ggplot(data = trimmed_k2_data, aes(x=distance)) +
geom_histogram(binwidth = 0.025, fill = "white", color = "black") +
coord_cartesian( ylim = c(0,1200) ) + scale_y_continuous(breaks = seq(0,1200,200)) +
labs(x = "K2P Distance", y = "Number of Orthologs", size= 3) +
theme(aspect.ratio = 1, panel.background = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(color = "black"),
axis.text = element_text(size = 8),
axis.title = element_text(size = 9, face = "bold")) +
geom_vline(aes(xintercept=mean(distance)), linetype="solid", colour="red", size=0.5, show.legend = FALSE)
trimmed_k2_data_hist
Fig3_plots <-ggarrange(Length_Site_Reg, GC_hist, trimmed_k2_data_hist, ncol = 3, widths = 1, heights = 1)
Fig3_plots

No legend visible in a ggplot set of code although it should be

I have run the following code :`
g <- ggplot(results_table, aes(x = "", y = Pct*100, fill = Criteria),width = 1) +
geom_bar(stat = "identity", color = Palcolor, fill = Palcolor) +
coord_polar(theta = "y", start = 0) +
theme_minimal() +
theme(legend.position = "bottom", legend.title=element_blank(), axis.title.x = element_blank(),,
axis.title.y = element_blank(), panel.border = element_blank(), panel.grid = element_blank(),
axis.text = element_blank(), axis.ticks = element_blank(),
plot.title = element_text(size = 14, hjust = 0.5, vjust = 0)) +
guides(fill = guide_legend(nrow = 4, byrow = TRUE)) +
theme(
legend.key.height = unit(0.3, "lines"), #smaller squares
legend.key.width = unit(0.7, "lines"), #smaller squares
legend.margin=margin(l = 40, unit='pt'),
legend.text = element_text(margin = margin(r = 60, unit = "pt"))) +
xlab("") +
ylab("") +
geom_text(aes(x = 1.70, y = Pct*100/2 + c(0, cumsum(Pct*100)[-length(Pct*100)]),
label = paste0(sprintf("%0.1f", round(Pct*100, digits = 1)),"%")),
size = 3.2) +
labs(title = gTitle)
}`
It created the pie chart as expected, but not the customized legend :
Any idea ?
The problem is that you set the custom color and fill palettes as arguments inside geom_bar. This way no legend will show up. You have to use scale_color/fill_manual to set the color palettes for the color/fill aesthetics.
Using ggplot2::mpg as example data and an example palette from RColorBrewer try this:
library(ggplot2)
library(dplyr)
# Example data
results_table <- mpg %>%
count(class) %>%
mutate(Pct = n / sum(n),
class = reorder(class, Pct)) %>%
rename(Criteria = class) %>%
arrange(desc(Pct)) %>%
mutate()
# Example palette as named vector to get the colors and categories right
Palcolor <- c("2seater" = "#8DD3C7", "minivan" = "#FFFFB3", "pickup" = "#BEBADA", "subcompact" = "#FB8072", "midsize" = "#80B1D3", "compact" = "#FDB462", "suv" = "#B3DE69")
# Example title
gTitle = "Example title"
g <- ggplot(results_table, aes(x = "", y = Pct*100, fill = Criteria),width = 1) +
geom_bar(stat = "identity") +
scale_color_manual(values = Palcolor) +
scale_fill_manual(values = Palcolor) +
coord_polar(theta = "y", start = 0) +
theme_minimal() +
theme(legend.position = "bottom", legend.title=element_blank(), axis.title.x = element_blank(),,
axis.title.y = element_blank(), panel.border = element_blank(), panel.grid = element_blank(),
axis.text = element_blank(), axis.ticks = element_blank(),
plot.title = element_text(size = 14, hjust = 0.5, vjust = 0)) +
guides(fill = guide_legend(nrow = 4, byrow = TRUE)) +
theme(
legend.key.height = unit(0.3, "lines"), #smaller squares
legend.key.width = unit(0.7, "lines"), #smaller squares
legend.margin=margin(l = 40, unit='pt'),
legend.text = element_text(margin = margin(r = 60, unit = "pt"))) +
xlab("") +
ylab("") +
geom_text(aes(x = 1.70, y = Pct*100/2 + c(0, cumsum(Pct*100)[-length(Pct*100)]),
label = paste0(sprintf("%0.1f", round(Pct*100, digits = 1)),"%")),
size = 3.2) +
labs(title = gTitle)
g
Created on 2020-05-16 by the reprex package (v0.3.0)

Calculate average points in each bin of a shot chart with R

I'm trying to make a shot chart in which the color gradient represents the average of success in each bin.
The next script gives the count of each bin, How can I change it to represent average of success in each bin instead the count? I attach the script output chart.
#rm(list=ls())
data3<-read.csv("data10.csv",header=T)
require(jpeg)
require(grid)
court<-rasterGrob(readJPEG("nba_court.jpg"),
width=unit(1,"npc"), height=unit(1,"npc"))
require(hexbin)
require(ggplot2)
ggplot(data3, aes(x=loc_x, y=loc_y)) +
# annotation_custom(court, -247, 253, -50, 418) +
stat_binhex(bins = 18, colour = "gray", alpha = 0.8) +
scale_fill_gradientn(colours = c("cyan","yellow","red")) +
guides(alpha = FALSE, size = FALSE) +
xlim(250, -250) +
ylim(-52, 418) +
geom_rug(alpha = 0.5) +
coord_fixed() +
ggtitle("Kobe Bryant shots") +
theme(line = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
legend.title = element_blank(),
plot.title = element_text(size = 17, lineheight = 1.2, face = "bold"))
DATASET SAMPLE:
data3 <- data.frame(matrix(data=c(-98,-75,-119,83,10,-103,-191,69,196,-21,-106,-127,-180,50,125,200,34,45,99,120,108,184,102,206,113,-3,93,94,164,101,82,146,108,24,56,77,67,200,250,-45,1,0,0,0,1,1,0,0,0,0,1,1,0,1,0,1,1,0,0,1),
nrow=20,ncol=3))
colnames(data3)<-c("loc_x","loc_y","shot_made_flag")
You should use stat_summary_hex and set fun=mean in order to calculate the effectiveness inside each bin:
# Create random data
set.seed(1)
data3 = data.frame(loc_x = runif(1000,-250,250),
loc_y = rnorm(1000,230,50),
shot_made_flag = rbinom(1000,1,.5))
require(hexbin)
require(ggplot2)
# The first two lines have changed (z = shot_made_flag and using fun = mean)
ggplot(data3, aes(x=loc_x, y=loc_y, z = shot_made_flag)) +
stat_summary_hex(fun = mean, bins = 18, colour = "gray", alpha = 0.8) +
scale_fill_gradientn(colours = c("cyan","yellow","red")) +
guides(alpha = FALSE, size = FALSE) +
xlim(250, -250) +
ylim(-52, 418) +
geom_rug(alpha = 0.5) +
coord_fixed() +
ggtitle("Kobe Bryant shots") +
theme(line = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
legend.title = element_blank(),
plot.title = element_text(size = 17, lineheight = 1.2, face = "bold"))
Result:
Edited the full answer due to new data and to reflect the desired output (mean inside each hex cell)

ggplot - using annotate across facets

This is a basic question but haven't been able to find the answer on here. I am creating a figure with ggplot from the following (overly simplified) data:
df.for.graph <- setNames(data.frame(matrix(ncol = 5,nrow = 8)), c("xp","yp","loc","cong","emotion"))
df.for.graph$xp <- c(948.7, 977.2, 1023.4, 953.3, 979.4,936.3, 911.6,877.2)
df.for.graph$yp <- c(923.0, 893.0, 294.9, 241.5, 898.6, 960.9, 154.4, 263.4)
df.for.graph$loc <- as.factor(c("Bottom", "Bottom", "Top", "Top", "Bottom", "Bottom", "Top", "Top"))
df.for.graph$cong <- as.factor(c("Incongruent","Congruent","Incongruent","Congruent", "Incongruent","Congruent","Incongruent","Congruent"))
df.for.graph$emotion <- as.factor(c("Angry", "Angry", "Angry", "Angry", "Happy","Happy", "Happy","Happy"))
My call to ggplot is as follows:
ggplot(df.for.graph,aes(x=xp,y=yp,color=loc,shape=cong)) +
geom_point() +
scale_color_manual(values=c("red","blue")) +
scale_shape_manual(values=c(1,4)) +
scale_fill_manual(values=c("green", "yellow")) +
scale_x_continuous(breaks = seq(from = 0, to = 1920, by = 160), limits=c(0,1920)) +
scale_y_reverse(breaks = seq(from = 0, to = 1200, by = 80), limits=c(1200,0)) +
labs(shape = "Congruence", color = "Probe Location",x = "X Position", y = "Y Position") +
facet_wrap(vars(emotion),nrow=2,ncol=1) +
theme(axis.title.x = element_text(face="bold",size=20),
axis.text.x = element_text(face="bold",size=15, color="black"),
axis.title.y = element_text(face="bold",size=20),
axis.text.y = element_text(face="bold",size=15, color="black"),
panel.background = element_rect(fill="white"),
panel.border = element_rect(colour = "black", fill=NA, size=2),
strip.text = element_text(face="bold",size=20),
legend.text = element_text(colour = "black", size=15),
legend.title = element_text(colour = "black", size=15)) +
annotate("rect",xmin=0, xmax=1920, ymin=0, ymax=599,alpha=.4) +
annotate("rect",xmin=0, xmax=1920, ymin=602, ymax=1200,alpha=.4)
This results in the following:
enter image description here
However I want the call to annotate to leave a line between the two rectangles on both facets of the plot. Currently it only leaves a line between the two on the top (Angry) facet. I thought that supplying the rect coordinates without specifying facets should draw the same two rectangles on each facet of the plot...
Any thoughts on how to make the bottom facet look like the top one?
Thanks in advance!
It's a matter of it displaying it properly on the device, i suggest you save it to a png or pdf. First save plot as object:
g1 = ggplot(df.for.graph,aes(x=xp,y=yp,color=loc,shape=cong)) +
geom_point() +
scale_color_manual(values=c("red","blue")) +
scale_shape_manual(values=c(1,4)) +
scale_fill_manual(values=c("green", "yellow")) +
scale_x_continuous(breaks = seq(from = 0, to = 1920, by = 160), limits=c(0,1920)) +
scale_y_reverse(breaks = seq(from = 0, to = 1200, by = 80), limits=c(1200,0)) +
labs(shape = "Congruence", color = "Probe Location",x = "X Position", y = "Y Position") +
facet_wrap(vars(emotion),nrow=2,ncol=1) +
theme(axis.title.x = element_text(face="bold",size=20),
axis.text.x = element_text(face="bold",size=15, color="black"),
axis.title.y = element_text(face="bold",size=20),
axis.text.y = element_text(face="bold",size=15, color="black"),
panel.background = element_rect(fill="white"),
panel.border = element_rect(colour = "black", fill=NA, size=2),
strip.text = element_text(face="bold",size=20),
legend.text = element_text(colour = "black", size=15),
legend.title = element_text(colour = "black", size=15)) +
annotate("rect",xmin=0, xmax=1920, ymin=0, ymax=599,alpha=.4) +
annotate("rect",xmin=0, xmax=1920, ymin=602, ymax=1200,alpha=.4)
And save:
ggsave(g1,file="g1.png",width=12,height=12)

Resources