Overlaying two lines with confidence interval on the same graph - r

I have plotted a line plot with confidence interval as below:
Here is the code I used:
Data_prob = read.table("group1.csv", header=TRUE, sep=",", na.strings="NA", dec=".", strip.white=TRUE)
p<-ggplot(Data_prob, aes(x=Trial, y=Data)) + theme_bw() + xlim(1, 49) + ylim(0.3, .95) +
theme(plot.title = element_text(color="black", size=14, face="bold.italic"), # plot title
axis.title.x = element_text(color="Black", size=25), # x label
axis.title.y = element_text(color="Black", size=25), # y label
axis.text.x = element_text(color = "black",face = "bold", # text style for x axis (removed face = "bold")
size = 22, angle = 0),
axis.text.y = element_text( color = "black",face = "bold", # text style for y axis
size = 22, angle = 0),
axis.line = element_line(color = "black", # line for x and y axis
size = 1, linetype = "solid"),
plot.caption = element_text(color = "black", size =11, face = "bold.italic"), # text style for caption
axis.ticks.length=unit(.25, "cm")
#axis.ticks = element_blank()
) +
theme(panel.border = element_blank(), # remove grid and background color
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
geom_ribbon(aes(ymin=Data-CI, ymax=Data+CI),
alpha=0.2, fill = "gold",color = "gray35", size = 0.1) +
geom_line(size=2, color="black")
print(p)
# Change axis labels
p <- p + labs(x = "Trial", y = "Go probability")
p
Here is what the data look like:
structure(list(Trial = 1:20, Data = c(0.500000027777778, 0.529220307827301,
0.519090892380421, 0.532167908861151, 0.598987738691911, 0.631452312399153,
0.669892859606973, 0.649994605133695, 0.675688232680895, 0.708304011267941,
0.720449809771278, 0.748081634160322, 0.761387966998141, 0.784275979741743,
0.786897508201414, 0.794196638795235, 0.785998558171792, 0.766138054176142,
0.790409435001615, 0.778745578955544), CI = c(5.44644605948509e-08,
0.073455696656296, 0.080875149623623, 0.073926617913334, 0.085753364225061,
0.068666346495005, 0.079656617789649, 0.077652237751934, 0.070180261163008,
0.071432599780653, 0.064943477844168, 0.064645277387821, 0.065096219183598,
0.065766579701286, 0.064325292909355, 0.066878706963396, 0.067698913200129,
0.07105300711211, 0.067063389995005, 0.069931673037628)), row.names = c(NA,
20L), class = "data.frame")
I would like to plot data from another group (group2.csv), so basically another line with confidence interval on the same graph to visually compare the two groups, ideally with a different line color. I've seen some examples on here but I couldn't get it to work. Could anyone help? Thank you!

Suppose you read your data up to two tibble from csv files.
library(tidyverse)
Data_prob1 =tibble(
Trial = 1:50,
Data = c(seq(0.5,0.8, length.out = 20), rep(0.8, 30))+rnorm(50,0,0.05),
CI = 0.1,
)
Data_prob2 =tibble(
Trial = 1:50,
Data = c(seq(0.8,1.2, length.out = 25), rep(1.2, 25))+rnorm(50,0,0.05),
CI = 0.08
)
You can combine such data like this
Data_prob = Data_prob1 %>% mutate(probe = "1") %>%
bind_rows(Data_prob2 %>% mutate(probe = "2")) %>%
mutate(probe = probe %>% fct_inorder())
Finally, create a chart
Data_prob %>% ggplot(aes(Trial, Data, fill=probe, color = probe))+
geom_line()+
geom_ribbon(aes(ymin=Data-CI, ymax=Data+CI, color=NULL), alpha=0.2)

Related

How to display a data group as points and another one as confidence ellipse? Issues with ggplot and ggsave

I am new to R, and I am trying to generate scatter plots with two variables, with the values of each variable grouped into 4 classes.
In particular, I am trying to achieve the following:
Display two groups as data points, two groups as confidence ellipses
Generate and save scatter plots having the same dimensions in term of plot frame size and plot area (i.e., x-axis long 8 cm, y-axis long 6 cm.).
Below you can find a reproducible version (you just need to define the output for the png file) of the code that works, but it shows data points and confidence ellipses for all data:
library(ggplot2)
out_path = YOUR OUTPUT DIRECTORY
#data frame
gr1 <- (rep(paste('B-12-B-002'), 10))
gr2 <- (rep(paste('B-12-M-03'), 10))
gr3 <- (rep(paste('b-b-d-3'), 10))
gr4 <- (rep(paste('h-12-b-01'), 10))
Run_type <- c(gr1,gr2,gr3,gr4)
axial_ratio <- runif(40,0,1)
Solidity <- runif(40,0,1)
Convexity <- runif(40,0,1)
sel_data_all <- data.frame(Run_type,axial_ratio,Solidity,Convexity)
fill_colors <- c('red','blue','green','orange');
#Plot
one_plot = ggplot(sel_data_all,aes(x = axial_ratio,y = Solidity))+
geom_point(aes(x = axial_ratio,y = Solidity, fill = Run_type, shape = Run_type), color = "black", stroke = 1,
size = 5, alpha = 0.4)+
stat_ellipse(data = sel_data_all, aes(x = axial_ratio, y = Solidity, fill = Run_type,colour=Run_type),geom = "polygon",alpha = 0.4,type = "norm",level = 0.6,
show.legend = FALSE) + #, group=Run_type , data = subset(sel_data_all, Run_type %in% leg_keys_man[1:7]),
scale_shape_manual(values=c(21,21,23,23))+
scale_fill_manual(values = fill_colors)+
scale_color_manual(values = fill_colors)+
coord_fixed(ratio = 1)+
theme(legend.position="top", # write 'none' to hide the legend
legend.key = element_rect(fill = "white"), # Set background of the points in the legend
legend.title = element_blank(), # Remove legend title
panel.background=element_rect(fill = "white", colour="black"),
panel.grid.major=element_line(colour="lightgrey"),
panel.grid.minor=element_line(colour="lightgrey"),
axis.title.x = element_text(margin = margin(t = 10), size = 12,face = "bold"), # margin = margin(t = 10) vjust = 0
axis.title.y = element_text(margin = margin(r = 10), size = 12,face = "bold"), # margin = margin(r = 10) vjust = 2
axis.text = element_text(color = "black", size = 10), # To hide the text from a specific axis do: axis.text.y = element_blank()
axis.ticks.length=unit(-0.15, "cm"), # To hide the ticks from a specific axis do: axis.ticks.y = element_blank()
#plot.margin = margin(t = 0, r = 1, b = 0.5, l = 0.5, unit = "cm"), # define margine of the plot frame t = top, r = right, b = bottom, l = left
)
#expand_limits(x = 0, y = 0)+ #Force the origin of the plot to 0
#xlim(c(0,1))+
#ylim(c(0,1)) # or xlim, limit the axis to the values defined
show(one_plot)
# Save plots
ggsave(
filename=paste("Axial_ratio","_vs_","Solidity",".png",sep=""),
plot = one_plot,
device = "png",
path = out_path,
scale = 1,
width = 8, # Refers to the plot frame, not the area
height = 6, # Refers to the plot frame, not the area
units = "cm",
dpi = 300,
limitsize = FALSE,
bg = "white")
Unfortunately, after several days of trying and reading the R documentation and forums, I cannot achieve this.
For the first task, I tried subsetting the data by modifying the geom_point and stat_ellipse functions,
geom_point(data = subset(sel_data_all, Run_type %in% c('B-12-B-002','B-12-M-03')),aes(x = axial_ratio,y = Solidity, fill = Run_type, shape = Run_type), color = "black", stroke = 1,
size = 5, alpha = 0.4)+ #
stat_ellipse(data = subset(sel_data_all, Run_type %in% c('b-b-d-3','h-12-b-01')), aes(x = axial_ratio, y = Solidity, fill = Run_type,colour=Run_type),geom = "polygon",alpha = 0.4,type = "norm",level = 0.6,
show.legend = FALSE) + #
but I end up with a duplicate of the legend (in grey colour).
Like this.
For my second issue, with the working version of the script at the top of the message,
Here is the plot that shows in the "Plots" window in RStudio:
But this is what is saved in the output directory.
A final note about the second issue: the script presented here is actually inserted in a for loop that generates multiple scatter plots made by unique pairs of two variables, and the data frame provided here is only partial, to make it easier for you to help. Unfortunately, this is what ggsave generates:
axial ratio vs convexity
ves_pct vs axial ratio
Can anybody help?
Thank you in advance to everyone!
EDIT:
So, thanks to MarBlo (which I thank a lot), I managed to get almost what I want, but there is still yet something I cannot figure out.
This is the last version of the code, with some adaptation to better fit the reasoning:
library(tidyverse)
set.seed(123)
gr1 <- (rep(paste("B-12-B-002"), 10))
gr2 <- (rep(paste("B-12-M-03"), 10))
gr3 <- (rep(paste("b-b-d-3"), 10))
gr4 <- (rep(paste("h-12-b-01"), 10))
Sample_ID <- c(gr1, gr2, gr3, gr4)
axial_ratio <- runif(40, 0, 1)
Solidity <- runif(40, 0, 1)
Convexity <- runif(40, 0, 1)
sel_data_all <- data.frame(Sample_ID, axial_ratio, Solidity, Convexity)
fill_colors <- c("#5bd9ca",
"#1e99d6","#1e49d6","#f2581b80","#e8811280","#e3311280","#fc000080")
sel_data_all <- sel_data_all |> add_column(Run_type = c(
rep("MAG", 10), rep("PMAG", 10),
rep("MAG", 10), rep("PMAG", 10)), .before = "Sample_ID")
one_plot = ggplot(
data = sel_data_all |> dplyr::filter(Run_type == "PMAG"),
aes(x = axial_ratio, y = Solidity)
) +
# CONFIDENCE ELLIPSE
stat_ellipse(
data = sel_data_all |> dplyr::filter(Run_type == "MAG"),
aes(x = axial_ratio, y = Solidity,
fill = Sample_ID),
geom = "polygon", type = "norm",
level = 0.6,
colour = 'white', # ellipse border
) +
# DATA POINTS
geom_point(aes(colour = Sample_ID,
shape = Sample_ID),
stroke = 0.5,
size = 3,
) +
scale_color_manual(values = fill_colors[1:3]) + # of Data points
scale_shape_manual(values = c(21, 21, 23, 23,21,23,22)) + # of data points
scale_fill_manual(values = fill_colors[4:7]) + # of ellipses
coord_cartesian(xlim=c(0,1))+
#scale_x_continuous(expand = expansion(mult = c(0.001, 0.05)))+
coord_cartesian(ylim=c(0,1))+
#scale_y_continuous(expand = expansion(mult = c(0.001, 0.05)))+
# Theme
theme(
legend.position = "top",
legend.key.size = unit(5, 'mm'), #change legend key size
# legend.key.height = unit(1, 'cm'), #change legend key height
# legend.key.width = unit(1, 'cm'), #change legend key width
legend.text = element_text(size=8),
legend.key = element_rect(fill = "white", colour = 'white'),
legend.background = element_rect(fill = "transparent"),
legend.title = element_blank(),
panel.background = element_rect(fill = "white", colour = "black"),
panel.grid.major = element_line(colour = "lightgrey"),
panel.grid.minor = element_line(colour = "lightgrey"),
axis.title.x = element_text(vjust = -1, size = 12, face = "bold"),
axis.title.y = element_text(vjust = 4, size = 12, face = "bold"),
axis.text = element_text(color = "black", size = 10),
axis.ticks.length = unit(-0.15, "cm"),
plot.margin = margin(t = 2, # Top margin
r = 4, # Right margin
b = 4, # Bottom margin
l = 4, # Left margin
unit = "mm"),
)+
guides(colour = guide_legend(nrow=2, byrow=TRUE)+
coord_fixed(ratio = 1))
ggsave(
filename=paste("snap",".png",sep=""),
plot = one_plot,
device = "png",
path = here::here(),
width = 8, # Refers to the plot frame, not the area
height = 8, # Refers to the plot frame, not the area
units = "cm",
#dpi = 300,
#limitsize = FALSE,
bg = "white")
Here is the saved plot
What I need, are the data points filled with the colour currently used for their border, and the border of all data points in black.
I tried to move around the aesthetics, but I ended up with the duplicate legend and more confusion.
Thanks in advance again for your help.
I have taken your data and added a variable called group which makes filtering in ggplot easier.
If you define x and y in ggplot(..,aes()) you do not have to define it again in geom_point.
In geom_point you give already a color to Run_type , the variable from which the legend should be made up. Because you use in geom_ellipse a different subset of the DF the legend would be updated and make again 4 legend entries instead of 2 for the variables only. color = Run_type can therefore be skipped.
I have added set.seed() which ensures that results are being comparable, although random numbers are generated for making up the DF.
library(tidyverse)
set.seed(123)
gr1 <- (rep(paste("B-12-B-002"), 10))
gr2 <- (rep(paste("B-12-M-03"), 10))
gr3 <- (rep(paste("b-b-d-3"), 10))
gr4 <- (rep(paste("h-12-b-01"), 10))
Run_type <- c(gr1, gr2, gr3, gr4)
axial_ratio <- runif(40, 0, 1)
Solidity <- runif(40, 0, 1)
Convexity <- runif(40, 0, 1)
sel_data_all <- data.frame(Run_type, axial_ratio, Solidity, Convexity)
fill_colors <- c("red", "blue", "green", "orange")
df <- sel_data_all |> mutate(group = c(
rep("Data", 10), rep("Conf", 10),
rep("Data", 10), rep("Conf", 10)
))
ggplot(
data = df |> dplyr::filter(group == "Data"),
aes(x = axial_ratio, y = Solidity)
) +
geom_point(aes(color = Run_type, shape = Run_type),
stroke = 1,
size = 5, alpha = 0.4
) +
stat_ellipse(
data = df |> dplyr::filter(group != "Data"),
aes(
x = axial_ratio, y = Solidity,
fill = Run_type
),
geom = "polygon", alpha = 0.4, type = "norm", level = 0.6,
show.legend = FALSE
) +
scale_shape_manual(values = c(21, 21, 23, 23)) +
scale_fill_manual(values = fill_colors) +
scale_color_manual(values = fill_colors) +
coord_fixed(ratio = 1) +
theme(
legend.position = "top",
legend.key = element_rect(fill = "white"),
legend.title = element_blank(),
panel.background = element_rect(fill = "white", colour = "black"),
panel.grid.major = element_line(colour = "lightgrey"),
panel.grid.minor = element_line(colour = "lightgrey"),
axis.title.x = element_text(margin = margin(t = 10), size = 12, face = "bold"),
axis.title.y = element_text(margin = margin(r = 10), size = 12, face = "bold"),
axis.text = element_text(color = "black", size = 10),
axis.ticks.length = unit(-0.15, "cm"),
)
The plot was then saved with equal width and height.
ggsave(
filename=paste("Axial_ratio","_vs_","Solidity",".png",sep=""),
plot = last_plot(),
device = "png",
path = here::here(),
width = 8, # Refers to the plot frame, not the area
height = 8, # Refers to the plot frame, not the area
units = "cm",
#dpi = 300,
#limitsize = FALSE,
bg = "white")
the saved png looks like this.
NEW EDIT
My understanding now is that you want two colors for geom_points and 2 different colors for stat_ellipse.
So the following will show a new attempt. If this is the right answer, I will erase most from above, to make this post better readable.
The ggsave -issue I regard as solved.
I have defined two different color-sets; one for geom_point and one for stat_ellipse. (There are 3 and 4 colors defined, although later in scale_color_manual and scale_fill_manual only 2 colors are needed.)
As for both geom_point and stat_ellipse a different DF is used, ggplot is called without any data or aes. Both will be defined individually when geom_point and stat_ellipse are called.
For stat_ellipse fill is used and for geom_point color is used as aes.
If you want to leave the one or the other legend out, you may use
show.legend = F in the respective geom.
xlim and ylim define axis limits.
guides() and theme_bw() make sure that the dark background of legend.key is erased.
I have tried to make the theme aa bit more concise.
library(tidyverse)
set.seed(123)
gr1 <- (rep(paste("B-12-B-002"), 10))
gr2 <- (rep(paste("B-12-M-03"), 10))
gr3 <- (rep(paste("b-b-d-3"), 10))
gr4 <- (rep(paste("h-12-b-01"), 10))
Sample_ID <- c(gr1, gr2, gr3, gr4)
axial_ratio <- runif(40, 0, 1)
Solidity <- runif(40, 0, 1)
Convexity <- runif(40, 0, 1)
sel_data_all <- data.frame(Sample_ID, axial_ratio, Solidity, Convexity)
fill_colors_points <- c("#5bd9ca", "#1e99d6", "#1e49d6")
fill_colors_ellipse <- c("#f2581b80", "#e8811280", "#e3311280", "#fc000080")
sel_data_all <- sel_data_all |> mutate(Run_type = c(
rep("MAG", 10), rep("PMAG", 10),
rep("MAG", 10), rep("PMAG", 10)
))
ggplot() +
stat_ellipse(
data = sel_data_all |> dplyr::filter(Run_type == "MAG"),
aes(
x = axial_ratio, y = Solidity,
fill = Sample_ID
),
geom = "polygon", type = "norm",
level = 0.6, show.legend = T
) +
geom_point(
data = sel_data_all |> dplyr::filter(Run_type == "PMAG"),
aes(
x = axial_ratio, y = Solidity,
color = Sample_ID,
shape = Sample_ID
),
stroke = 0.5, size = 3,
) +
scale_color_manual(values = fill_colors_points[1:2]) + # of Data points
scale_fill_manual(values = fill_colors_ellipse[1:2]) + # of ellipses
xlim(0,1) + ylim(0,1) +
guides(color = guide_legend(override.aes = list(fill = NA))) +
theme_bw() +
theme(
legend.position = "top",
legend.key.size = unit(5, "mm"), # change legend key size
legend.text = element_text(size = 8),
legend.title = element_blank(),
panel.background = element_rect(fill = "white", colour = "black"),
panel.grid = element_line(colour = "lightgrey"),
axis.title.x = element_text(vjust = -1, size = 12, face = "bold"),
axis.title.y = element_text(vjust = 4, size = 12, face = "bold"),
axis.text = element_text(color = "black", size = 10),
axis.ticks.length = unit(-0.15, "cm"),
) +
coord_fixed(ratio = 1)

Dodge failing in violin plot

I would like to plot the congruence effects (incongruent minus congruent) as a violin plot per combination of stimulus age and response type. This is what my code looks like so far. I am not yet satisfied with the representation. How can I change it so that for each of the four conditions (adult frown, adult smile, child frown, child smile) I get the corresponding violin plot horizontally next to each other? Thanks in advance for the help. Attached is the code and an excerpt from the data frame.
violin plot
dataset$congruency_effect <- ifelse(dataset$congruency == "congruent", dataset$avgAmplitude, -dataset$avgAmplitude)
p <- ggplot(dataset, aes(x = stimulusResponse, y = congruency_effect, fill = congruency_effect, group = stimulusAge)) +
geom_violin() +
geom_point(position = position_dodge(width = 0.75), size = 3, stat = "summary", fun.y = "mean") +
scale_fill_manual(values = c("#F8766D", "#00BFC4")) +
ggtitle("Conventional EEG 350-450 ms") +
scale_y_continuous(limits = c(-5, 5)) +
facet_wrap(~stimulusAge, scales = "free_x")
EEG_Conventional450_age_response <- p + theme(
# Set the plot title and axis labels to APA style
plot.title = element_text(face = "bold", size = 16),
axis.title = element_text(face = "bold", size = 14),
# Set the axis tick labels to APA style
axis.text = element_text(size = 12),
# Set the legend title and labels to APA style
legend.title = element_text(face = "bold", size = 14),
legend.text = element_text(size = 12),
# Set the plot and panel backgrounds to white
panel.background = element_rect(fill = "white"),
plot.background = element_rect(fill = "white")
)
EEG_Conventional450_age_response
excerpt data frame
several permutations of arguments in ggplot
This has to do with the grouping aesthetic. Remove it, and your plot works.
library(ggplot2)
set.seed(42)
dataset <- data.frame(stimulusResponse = rep(c("frown", "smile"), each = 20),
congruency_effect = rnorm(40),
stimulusAge = rep(c("baby", "adult"), 20))
## removed group = stimulusAge
ggplot(dataset, aes(x = stimulusResponse, y = congruency_effect)) +
geom_violin() +
geom_point(position = position_dodge(width = 0.75), size = 3, stat = "summary") +
facet_wrap(~stimulusAge, scales = "free_x")

How to draw color line with size in R

I have a data with over 700 observations but below is a sample. Using geom_curve I want to make a plot where the line size(total_trips) corresponds to a color say 3 different colors. For instance between 0-100 (total_trips) can have a color of red
df <- data.frame(
origin_x = c(659627.8,642136.2,648774.7,659627.8,659627.8,658455.7,659627.8,659620.6,661641.8,656246.4),
origin_y = c(6473200,6473200,6462166,6473200,6473200,6467413,6473200,6467163,6479577,6487039),
dest_x = c(642136.2,659627.8,659627.8,648774.7,659620.6,659627.8,658455.7,659627.8,659627.8,659627.8),
dest_y = c(6456563,6473200,6473200,6462166,6467163,6473200,6467413,6473200,6473200,6473200
),
total_trips = c(4002,49878,2011,500,100,3000,2500,654,900,600))
I tried
ggplot() + geom_sf(data=shapefile, colour='grey', fill='grey93', size = 0.25) +
geom_curve(
data = df),
aes(
x = origin_x,
xend = dest_x,
y = origin_y,
yend = dest_y,
size = n,
colour= as.factor(c('red','blue'))),
curvature = 0.3
) + scale_alpha_continuous(range = c(0.09,1)) +
theme(
axis.title = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
plot.title = element_text(hjust = 0.5, size = 6),
plot.caption = element_text(hjust = 1),
plot.caption.position = 'plot',
axis.ticks = element_blank(),
panel.background = element_rect(fill = 'white'),
panel.grid = element_blank(),
plot.background = element_rect(color = NA, size = 0.5, fill=NA),
panel.border = element_rect(color = 'black', fill = NA, size=0.2) ,
legend.position = c(0.89,0.15),
legend.key.size = unit(0.4, 'cm'),
legend.text = element_text(size=7)
) +
annotation_scale(location = 'br', style = 'ticks') + coord_sf(crs=3301) +
annotation_north_arrow(location = 'tr', width = unit(0.20, 'cm'),height = unit(0.5,'cm'))
If I understand correctly - you want to change the colour of the line according to a categorised continuous variable (total_trips), we can do this:
Use cut to categorise the variable and give labels to the groups
Add this new variable to the aes(colour =.
library(dplyr)
library(ggplot2)
df <- df |> mutate(trips = cut(total_trips, c(0, 2000, 5000, 50000),
labels = c("0-2k", "2k-5k", "5k-50k")))
ggplot() +
geom_curve(data = df, aes(x = origin_x,
xend = dest_x,
y = origin_y,
yend = dest_y,
size = total_trips,
colour = trips
))
Output:
Not sure if this is what you want, though – your sample dataset doesn't contain the variable n that you mention in size = n, and you haven't provided us with shapefile.

Add grid lines to minor breaks only (ggplot)

I was trying to make a chart as the below in ggplot. I wanted the y labels to show the entire set of values from 1 to 50 but I only wanted to generate horizontal gridlines every 10 numbers. I thought adding minor_breaks and then controlling the theme would work. However, setting the major grid lines to element_blankseems to be overriding the minor gridlines as well. I found some questions here where people have asked about adding more gridlines than labels, but I want the reverse.
How can I set the number of gridlines to be smaller than the number of breaks? Thanks!
Here is the code for the plot:
library(nsRFA)
library(ggplot2)
library(dplyr)
data(hydroSIMN)
annualflows %>% ggplot(aes(x = anno, y = cod)) +
geom_point(
shape = 45,
size = 5,
col = "blue"
) +
scale_y_reverse(
breaks = 1:50,
labels = 1:50,
minor_breaks = seq(10, 50, by = 10)
) +
scale_x_continuous(breaks = seq(1920, 1980, by = 10)) +
labs(
x = "Year",
y = "Code"
) +
theme(
panel.background = element_blank(),
panel.border = element_rect(fill = NA),
text = element_text(size = 10),
panel.grid.major.x = element_line(color = "grey80"),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_line(color = "grey80") # This doesn't work
)
From reading this https://github.com/tidyverse/ggplot2/issues/403, it would appear that there are some issues surround minor_breaks. However, using geom_hline() should get you what you want.
library(nsRFA)
library(ggplot2)
library(dplyr)
data(hydroSIMN)
minors<-seq(10,50,by=10)
annualflows %>% ggplot(aes(x = anno, y = cod)) +
geom_point(
shape = 45,
size = 5,
col = "blue"
) +
scale_y_reverse(
breaks = 1:50,
labels = 1:50,
minor_breaks = seq(10, 50, by = 10)
) +
scale_x_continuous(breaks = seq(1920, 1980, by = 10)) +
labs(
x = "Year",
y = "Code"
) +
theme(
panel.background = element_blank(),
panel.border = element_rect(fill = NA),
text = element_text(size = 10),
panel.grid.major.x = element_line(color = "grey80"),
#panel.grid.major.y = element_blank(),
#panel.grid.minor.y = element_line(color = "grey80") # This doesn't work
)+
geom_hline(mapping=NULL, yintercept=minors,colour='grey80')

how to get and modify size legend in ggplot2

I am having some trouble displaying the size legend in my plot and changing the name of my size legend.
My data is corp already has a size column which is either of the values 5, 10, 20
I am using ggplot2 I already have a legend for the color
I want to add one for the size and manually change the size labels..
How do I increase the the font of the legend ? It's super tiny (FIN, IND UTIL)
also the 15 for the size shouldnt be there i want to just omit it and display both legends side by side.
p <- ggplot(corp, aes(x=annRisk, y=annRet, color = corp$subsector1, face = "bold"))
p<- p + geom_point(aes(size = corp$Colsize), alpha = 0.55)
p<-p + scale_size(range = c(8, 20))
p<-p + scale_colour_manual("", values = c("UTIL" = "#fdcc8b", "IND" = "#fc8d59", "FIN" = "#d7301f",
"ABS" = "#74a9cf", "CMBS" = "#0570b0", "LA" = "#8c96c6", "SOV"= "#88419d", "SUPRA" = "#b3cde3"))
p<-p+labs(title = "SOME TITLE")
print(p)
p<-p+theme(plot.title = element_text(face = "bold", size = 20))
p<-p+theme(axis.title.x = element_text(size = 20), axis.text.x = element_text(size = 13))
p<-p+theme(axis.title.y = element_text(size = 20), axis.text.y = element_text(size = 13))
p<-p+geom_text(aes(label=ifelse(Colsize>=10,subsector2,"")), size=5,color = "black", face = "bold", hjust=-0.1, vjust = 0.1)
p<-p+scale_x_continuous(labels = percent, name = "Annualized Risk", limits = c(0.05, 0.09))
p<-p+scale_y_continuous(labels = percent, name = "Annualized Return", limits = c(0.04, 0.08))
p<-p+ theme(legend.position = "bottom")
print(p)
Although I can't use your data yet, you can try adding the following code:
p <- p + theme(legend.position = "bottom",
legend.title = element_blank(),
legend.text = element_text(size=14),
legend.box = "horizontal")
p <- p + scale_size_manual(values=c(5,10,20), labels = c("5","10","20"))

Resources