how to get and modify size legend in ggplot2 - r

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

Related

Creating Dual Axis plot (bar and line)

I want to create a dual axis plot in ggplot R with a dual bar and line plot, like this one created in excel.
The y axis scales are different.
my data is as follows;
I've created a bar plot and line plot. But unsure on how to put them together (I've tried man various ways and they don't seem to work).
Here is my code for the bar plot.
inf_conc <- ggplot(data=data, aes(x=Day, y=inf)) +
geom_bar(stat="identity", width=0.4, color="red3", fill="red3") +
ggtitle("Influent Microplastic Concentration \n and Flow Rate") +
# \n splits long titles into multiple lines
xlab("Day") +
ylab("Microplastic Concentration (MPs/L)") +
scale_y_continuous(limits =c(0, 50), breaks = seq(0, 50, 5))
inf_conc + theme(axis.text = element_text(size = 20, colour = "black"),
plot.title = element_text(size =25, hjust = 0.5,
face = "bold"), axis.title = element_text(size = 20,
face = "bold", margin = 5))
inf_conc + theme(axis.text = element_text(size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, face = "bold"),
axis.title = element_text(size = 20, face = "bold", margin = 20))
and here is the code for the line plot:
inf_flow <- ggplot(data=data, aes(x=Day, y=flow, group = 1)) +
geom_line(stat = "identity", colour ="blue4") +
geom_point(colour ="blue4") +
ylab("Inlet flow L/s")+
xlab("Day")+
scale_y_continuous(limits=c(0,800), breaks = seq(0, 800, 100))
inf_flow + theme(axis.text = element_text(size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, face = "bold"),
axis.title = element_text(size = 20, face = "bold", margin = 5))
inf_flow + theme(axis.text = element_text(size = 20,
colour = "black"), plot.title = element_text (size =25, hjust = 0.5,
face = "bold"), axis.title = element_text(size = 20, face = "bold",
margin = 20))
Can anyone help with how I can get these onto one dual axis graph please.
GGplot doesn't make it especially easy, but you can do it:
library(ggplot2)
my_dat <- data.frame(
Day = paste("Day",rep(1:3, each=3), rep(c("(AM)", "(Midday)", "(PM)"), 3), sep= " "),
day_num = 1:9,
inf = seq(from = 13,to = 45, length=9),
flow = runif(9, 580, 740)
)
ggplot() +
geom_bar(data=my_dat, aes(x=day_num, y=inf, fill = "Influent Concentration"), stat="identity", width=.6) +
geom_line(data=my_dat, aes(x=day_num, y=flow*(50/800), colour="FLow Rate. L/s")) +
scale_fill_manual(values="red") +
scale_colour_manual(values="blue") +
scale_x_continuous(breaks=1:9, labels=my_dat$Day) +
scale_y_continuous(sec.axis = sec_axis(trans = ~.x*800/50, name = "Flow Rate L/S"), limits = c(0,50), name = "Influent. MPs/L") +
labs(fill="", colour="", x="") +
theme(legend.position="bottom",
axis.text.x = element_text(angle=45, hjust=1))
Created on 2023-01-17 by the reprex package (v2.0.1)
The main things you have to do are to
Transform the second-axis series to have the same range(ish) as the first-series axis. In your case, the excel graph had the second y-axis going from 0-800 and the first y-axis going from 0-50, so the transformation is simple, you multiply the second series values by 50/800.
In the scale_y_continuou() function there is an argument sec.axis which allows you to plot a second axis on the right-hand side of the plot. Here, you need to specify the trans argument to transform the values you're plotting back into the original values. That's what trans = ~.x*800/50 does.
EDIT: Modifying OP's code
I modified your code as much as I can without actually having the data. The picture of the data that you provided does not give enough information about the data, if you use dput(data) and post the results, I could likely help more. For now, try this:
inf_plot <- ggplot(data=data, aes(x=Day))+
geom_bar(aes(y=inf, fill="Influent conc"), stat = "identity", width=0.4)+
geom_line(aes(y=flow*(50/800), colour="flow rate"), size = 1.4, group=1)+
ggtitle("Influent Microplastic Concentration \n and Influent Flow Rate")+
xlab("\n\nDay") +
ylab("Microplastic Concentration (MPs/L)\n\n")+
scale_fill_manual(values="red4") +
scale_colour_manual(values="blue4") +
scale_y_continuous(sec.axis = sec_axis(~.*800/50, name = "Inlet flow rate (L/s)\n\n"), limits = c(0,50))
inf_plot + theme(axis.text = element_text( size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, vjust = 5, face = "bold"),
axis.title = element_text (size = 20, face = "bold"),
plot.margin =unit(c(1.5, 1.5, 1.5, 1.5), "cm"),
legend.position = "bottom")
The answer was a great help in how to transform my axis.
Initially produced the graph a slightly different way, but incorporated the same transformation of axis.
However, I can't seem to get the legend to appear at the bottom of the graph with the following code.
inf_plot <- ggplot(data=data, aes(x=Day))+
geom_bar(aes(y=inf, fill="Influent conc"), stat = "identity", width=0.4,
colour="red4", fill = "red4")+
ggtitle("Influent Microplastic Concentration \n and Influent Flow Rate")+
xlab("\n\nDay") +
ylab("Microplastic Concentration (MPs/L)\n\n")+
geom_line(aes(y=flow*(50/800), colour="flow rate"), size = 1.4, colour ="blue4", group = 1)+
scale_fill_manual(values="red4") +
scale_colour_manual(values="blue4") +
scale_y_continuous(sec.axis = sec_axis(~.*800/50, name = "Inlet flow rate (L/s)\n\n"), limits = c(0,50))
inf_plot + theme(axis.text = element_text( size = 20, colour = "black"),
plot.title = element_text (size =25, hjust = 0.5, vjust = 5, face = "bold"),
axis.title = element_text (size = 20, face = "bold"),
plot.margin =unit(c(1.5, 1.5, 1.5, 1.5), "cm"),
legend.position = "bottom")
enter image description here

Facet_Wrap title overlapping with y-axis in ggplotly?

I am currently using a facet_wrap to knit data (html) to an Rmarkdown document. I am looking to use facet_wrap and ggplot to show this data.
This is how the data looks just in ggplot (not plotly):
However, when I use plotly the titles of each plot intersect with the y-axis making interpretability difficult
Here is the code to the first plot not using plotly
plot <- ggplot(dataframe, aes(x = week, y = measure))+
geom_line(size = 1.25, aes(color = "orange"))+
geom_point(size = 1.50)+
theme_economist()+
geom_smooth(method = 'auto', se = FALSE, size = .50)+
scale_x_continuous(breaks=seq(0,13,1))+
scale_y_continuous(labels = scales::dollar_format(scale = .0001, suffix = "K"))+
facet_wrap(vars(category), scales = "free", ncol = 3, nrow = 6)+
theme(legend.position = "none")+
ggtitle('Title')+
theme(
panel.grid.major = element_line(linetype = "dotted"),
axis.title.x = element_text( size = 10, margin=margin(30,0,0,0)),
axis.title.y = element_text( size = 10, margin=margin(0,30,0,0)),
axis.text = element_text( size = 10),
plot.title = element_text( size = 14, margin=margin(0,0,35,0), hjust = 0.5),
panel.background = element_rect(fill = NA),
strip.text = element_text(size=10)
)
Then here is what I do to conver it to plotly
ggplotly(plot)
Some random data:
require(stats)
r <- function(x) {abs(as.numeric(arima.sim(n=x, list(order=c(1,0,0),ar=0.95)))+10)}
dataframe = data.frame(week = rep(1:13,6), measure = r(13*6), category = rep(as.character(1:6),each=13))
Although I was not able to reproduce the overlapping y-axis labels, you can set the margins between the faceted plots by setting panel.margin.y and panel.margin.x inside the theme():
plot <- ggplot(dataframe, aes(x = week, y = measure))+
geom_line(size = 1.25, aes(color = "orange"))+
geom_point(size = 1.50)+
theme_economist() +
geom_smooth(method = 'auto', se = FALSE, size = .50)+
scale_x_continuous(breaks=seq(0,13,1))+
scale_y_continuous(labels = scales::dollar_format(scale = .0001, suffix = "K"))+
facet_wrap(vars(category), scales = "free", ncol = 3, nrow = 6)+
theme(legend.position = "none")+
ggtitle('Title')+
theme(
panel.grid.major = element_line(linetype = "dotted"),
axis.title.x = element_text( size = 10, margin=margin(30,0,0,0)),
axis.title.y = element_text( size = 10, margin=margin(0,30,0,0)),
axis.text = element_text( size = 10),
plot.title = element_text( size = 14, margin=margin(0,0,35,0), hjust = 0.5),
panel.background = element_rect(fill = NA),
strip.text = element_text(size=10), panel.margin.x = unit(1,"lines"), panel.margin.y = unit(0,"lines")
)
ggplotly(plot)
You can fine tune the margins to suit your plot.
Before:
> ggplotly(plot)
After:
> ggplotly(plot)

How do I remove specific tick labels in ggplot2?

I have the following bubble plot that shows the abundance percentage of microbes across different samples. However, I want to remove the tick labels called "Archaea" and "Other taxa" (located at either ends of the bubble plot) since the labels for both can be placed in the x-axis strip text instead. I used the following code to produce the plot:
ggplot(En.TaxMisc.NoC.RelAb.filtered.tidy$CombinedMisc,
aes(x = factor(Taxonomy, levels = En.TaxMisc.order$Taxonomy),
y = SampleSource, size = RelAb)) +
geom_point(colour = '#abd9e9') +
facet_grid(SampleType ~ Level,
labeller = labeller(SampleType = SampleType.NoC.labels),
scale = 'free', space = 'free') +
scale_x_discrete(name = NULL) +
scale_y_discrete(position = 'left', name = NULL) +
scale_size_continuous(name = str_wrap('Relative abundances (%)', width = 10),
breaks = c(1:8), range = c(0.75, 20)) +
guides(size = guide_legend(nrow = 1)) +
theme(legend.position = 'bottom',
legend.background = element_rect(colour = 'grey70'),
legend.title = element_text(size = 8, hjust = 1),
legend.text = element_text(size = 7, hjust = 0),
legend.spacing.x = unit(2.5, 'mm'),
legend.box = 'horizontal',
strip.background = element_rect(colour = 'grey55'),
strip.text.x = element_text(size = 8),
strip.text.y = element_text(size = 8),
axis.text.x.bottom = element_text(angle = 90, hjust = 1,
vjust = 0.3, size = 8),
axis.text.y.left = element_text(size = 8),
axis.ticks = element_blank(),
panel.grid.major.x = element_line(linetype = 1),
panel.border = element_rect(linetype = 1, fill = NA),
panel.background = element_blank())
I had tried to use scale_x_discrete(labels = c("Archaea" = NULL, "Other taxa" = NULL) but this resulted in all the tick labels being removed. I had also looked into using the rremove() function and the axis_ticks theme components, but neither appear to possess arguments for specifying tick labels.
I'd appreciate suggestions or advice anyone can give me!
There's a fair bit of extraneous detail in the question, but if you're just looking to remove (or customize!) tick labels, all you need is to add a labels argument to scale_x_discrete.
Self-contained example:
library(ggplot2)
ds = data.frame(
xVar = as.factor(rep(LETTERS[1:5],10)),
y = rnorm(50)
)
my_custom_labels = c("","level B","level C","level D!","")
ggplot(data = ds) +
geom_point(aes(x = xVar,y = y)) +
scale_x_discrete(labels = my_custom_labels)

R: Two y-axes plot using scale_y_continuous(sec.axis) and coord_trans(log10)

I am trying to plot a 2y-axes plot; on the left, the actual values, and on the right, the % values. In addition to this, I need to apply coord_trans on the left y-axis for a better visualization of small values. However, when I do it, the labels on the right do not show up.
Here the data (example)
Here the code
DAXIS <- ggplot(x1, aes(hour, value_T, colour=season, linetype = variable)) +
geom_line(size = 1) +
scale_linetype_manual(c("var"), values=c("solid", "dashed", "dotted"))+ # here to change one name
geom_point(aes(shape = season), size = 1)+
labs(x = "hour", y = "T") +
scale_x_continuous(breaks = c(0, 6, 12, 18, 23), labels= c(0, 6, 12, 18, 24))+
scale_y_continuous("T",
sec.axis = sec_axis(~./2.341598, name = " [%] ",
breaks=c(0.2135294, 0.4270588, 0.6405882, 0.8541176,1),
labels = function(b) { paste0(round(b * 100, 0), "%")}))+
#coord_trans(y = "log10", breaks=c(0.5,1,1.5,1.903738), labels = c(0.5,1,1.5,1.9))+ # attemp 1
#coord_trans(y = "log10")+ # attemp 2
scale_color_aaas()+
theme_bw()+
theme(legend.direction = "horizontal", legend.position = "bottom", legend.key = element_blank(),
legend.background = element_rect(fill = "white", colour = "gray30")) +
theme(legend.position="bottom",
text=element_text(size=18),
axis.text.x = element_text(size=15),
axis.text.y = element_text(size=15))
DAXIS
Here the output without coord_trans
Here the output with coord_trans
Any help is very much appreciated

Adjusting white space between titles and the edge of the plot

I want to create space between the titles (the axis title and the plot title) and the edge of the plot. I tried vjust on axis.title and plot.title with no luck. Nothing really changed in the plot when I tried various values for vjust. I also tried plot.margin, but nothing seemed to happen with it either.
Data:
data = data.frame(Category = c(0,1), value = c(40000, 120000))
data$Category = factor(data$Category, levels = c(0,1), labels = c("One-time", "Repeat"))
Plot:
p = ggplot(data, aes(Category, Value)) +
geom_bar(stat = "identity", width = 0.5, position=position_dodge(width=0.9)) +
geom_text(aes(label=Value), position=position_dodge(width=0.9), family = "mono", vjust=-0.5) +
ggtitle("Title") +
scale_y_continuous(expand = c(0,0), limits = c(0,150000)) +
scale_x_discrete(expand = c(0,0), limits = c("One-time", "Repeat")) +
xlab("X axis Title") +
ylab("Y axis Title")
Theme:
p + theme(
panel.grid.major = element_line(linetype = "blank"),
panel.grid.minor = element_line(linetype = "blank"),
axis.title = element_text(family = "sans", size = 15),
axis.text = element_text(family = "mono", size = 12),
plot.title = element_text(family = "sans", size = 18),
panel.background = element_rect(fill = NA)
)
You want to do this using margin
p + theme(
panel.grid.major = element_line(linetype = "blank"),
panel.grid.minor = element_line(linetype = "blank"),
axis.title.x = element_text(family = "sans", size = 15, margin=margin(30,0,0,0)),
axis.title.y = element_text(family = "sans", size = 15, margin=margin(0,30,0,0)),
axis.text = element_text(family = "mono", size = 12),
plot.title = element_text(family = "sans", size = 18, margin=margin(0,0,30,0)),
panel.background = element_rect(fill = NA)
)
Note that margin requires a four inputs and they specify the space in the order top,right,bottom,left. Also note I'm using the developmental ggplot2 version so my title default is left justified. 'hjust' and 'vjust' worked in older versions of ggplot2.
You can also give a "-ve" value to margin argument to pull the title closer to the plot.
gg_1 +
theme(plot.title = element_text(size = 12,
hjust = 0.5,
family = fam_3,
face = "bold",
margin = margin(0,0,-10,0))

Resources