Mix different font sizes/faces in plot caption - r

Using the code below to generate a heat map in R. It works well. The first section is the metric that I use to color the map. My question is how would I have the caption read like below. I know that one would put the first line in front of the other in the section that begins with caption = Paste ("Source...")However, how to have the first line be bigger and bold font is escaping me.
map50<- merge(us50, pop1)
breaks <- seq(-.01, .05, by = .01)
map50$c1<- cut(map50$growth, breaks, label=c("-1% to 0%", "0% to 1%", "1%
to 2%", "2% to 3%", "3% to 4%","4% to 5%"))
library(ggplot2)
b= ggplot(data= map50, aes(x=long, y=lat, group=group))
d= b+geom_polygon(aes(fill=c1),
colour=alpha("black"),size=.05)+scale_fill_brewer(palette="YlOrRd",name="y/y
growth rates")+coord_equal()
d= d+labs(x = NULL, y = NULL, fill = NULL,
title = "Average Employment Growth By State Q3 2018",
subtitle = "For Private, All Industries",
caption = paste("Source: BLS Quarterly Census of Employment and
Wages\nProduced By: #NVlabormarket"))
d= d+theme_void()
d=d+theme(text = element_text(family = "NimbusSan", size = 10),
plot.title = element_text(size = 20, face = "bold"),
plot.margin = unit(c(0, 0.25, 0.0, 0.25), "in"),
panel.border = element_rect(fill = NA, colour = "#cccccc"),
legend.text = element_text(size = 8),
legend.position=c(.93, 0.2))
ggsave("Q32018EmploymentGrowthHeat-YlOrRdu.pdf")

You can plot first caption (bold line) using caption argument and second line using tag argument in labs function. Next you have to manually specify tag position using plot.tag.position.
library(ggplot2)
ggplot(mtcars, aes(cyl, mpg)) +
geom_point() +
labs(caption = "Source: BLS Quarterly Census of Employment and Wages",
tag = "Produced By: #NVlabormarket") +
theme(plot.caption = element_text(vjust = 4, size = 9, face = "bold"),
plot.tag = element_text(size = 9),
plot.tag.position = c(0.89, 0))

Related

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

Plot a raster stack with values above a certain threshold in R ggplot

I have a raster stack of 8 TIF images. I am plotting them using the gplot. As you can see, the raster values are from 0 to 8, but its impossible to have a place where the pH value of the groundwater is around 0.
So, what I want to do is filter the values of the raster files and plot only the regions with pH above 5.
Also, I want to label the regions with pH values below 5 in a different color (say, grey) and add a corresponding 'No Data Available' in the legend. Is it possible to do that?
I tried doing something like pfiles <- pfiles1 > 5 and then plot it. But it throws an error: Error: Discrete value supplied to continuous scale. I want to use gradient color.
The code I am using:
library(raster)
library(rasterVis)
library(viridis)
library(ggplot2)
library(ggpubr)
shp = broom::tidy(shapefile("G:/WB_dist_utm.shp"))
rfiles = list.files(path = "G:/GW_IDW", pattern = "*.tif", full.names = TRUE)
atr = c(paste("Year", sep = "_", seq(2005, 2019, 2)))
pfiles1 = stack(rfiles[c(33:40)])
names(pfiles) = atr
ph = gplot(pfiles) +
geom_raster(aes(fill = value)) +
geom_path(data=shp, aes(long, lat, group=group), color = 'black') +
facet_wrap(~ variable, ncol = 4) +
scale_fill_gradientn(colours = rev(magma(30)), na.value = "transparent", n.breaks = 6) +
theme_bw() +
theme(axis.text = element_blank(), legend.position = "right", legend.direction = "vertical",
axis.title = element_blank(),
legend.key.height = unit(2, "cm"), legend.key.width = unit(1, "cm"),
legend.title = element_blank(), legend.text = element_text(size = 26),
strip.text = element_text(size = 28, face = "bold"),
plot.title = element_text(size = 23, face = "bold"),
plot.subtitle = element_text(size = 15), plot.caption = element_text(size = 10)) +
labs(title = "Ground Water Quality in West Bengal: 2005 - 2019",
subtitle = "pH values\n",
caption = "Data source: ENVIS Centre on Control of Pollution Water, Air and Noise.
http://www.cpcbenvis.nic.in/water_quality_data.html
Prepared by: Akhilesh Kumar") +
coord_equal()
This is the plot I am getting. I want to plot only the pH values > 5 and show the rest of the region in grey with a legend entry as "No Data Available".
Thank you.

In R, ggplot for a population pyramid: how to align labels near to the axis with geom_bar geom_label after flipping the coordinates

I am making a sort of population pyramid using ggplot (plotrix doesn't allow me to do fancy labels etc), then I start with a geom_bar with labels and later I flip the coordinates. Sadly, labels almost cannot being seeing. I would like to move those labels near to the "y- axis" in the middle, that now is showing the age groups.
Data is here: d <- data.frame(age.grp2 = c("1-10", "11-20", "21-30", "31-40", "41-50", "1-10", "11-20", "21-30", "31-40", "41-50"),
sex = c("Female","Female","Female","Female","Female","Male","Male","Male","Male","Male" ),
n.enroll = c(288,500,400,300,200,300,460,300,200,300),
proportion = c(17.1,29.6,23.7,17.8,11.8,51,47.9,42.9,40,60),
proportion2 = c(-17.1,-29.6,-23.7,-17.8,-11.8,51,47.9,42.9,40,60)) My code is this one: ggplot(d, aes(x = age.grp2, y = proportion2, fill = sex)) +
geom_bar(position = position_dodge(width=1), stat='identity') +
geom_label(aes(label = paste(n.enroll," (",proportion,"%)", sep=""), group = factor(sex)),
fill="white", colour = "black",
position= position_dodge(width=1),
size = 3) +
scale_fill_manual(values=c("#BFD5E3", "grey")) +
facet_share(~sex, dir = "h", scales = "free", reverse_num = TRUE) +
coord_flip() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
#panel.border = element_blank(),
panel.background = element_blank(),
legend.position = "none",
#axis.line.x = element_line(color = "black"),
axis.ticks.y = element_blank(),
axis.text.x = element_text(colour = "black", size = 8, face = "bold", angle=0, hjust=0.5),
axis.text.y = element_text(colour = "black", size = 8, face = "bold"),
axis.title.x = element_text(size = 14, face="bold", margin = margin(t = 30, r = 20, b = 10, l = 20)),
plot.margin = unit(c(1,1,1,1),"cm")) +
labs(y = "Enrollment percentage within sex",x="") I am attaching also the plot, where we can see in females the label in the age group 11-20 is cut. I would like to have all labels near to the age group labels, within each bar: female labels moved to the right and male labels move it to the left. Also, I would like to have each x-axis extended to 100% or at least in same range, in females goes up to 30% and in males goes up to 60%. Thanks for all the comments
Here's a minimal solution using the base ggplot package, without most of your formatting. The key part is to add a conditional y = ... into the geom_label(aes()) section:
d %>%
mutate(
label = str_c(n.enroll, " (", proportion, "%)"),
label_loc = if_else(sex == "Female", -9.5, 3),
proportion_for_chart = if_else(sex == "Female", -proportion, proportion)
) %>%
ggplot(aes(x = age.grp2, y = proportion_for_chart, fill = sex)) +
geom_col(show.legend = FALSE) +
geom_label(aes(y = label_loc, label = label), size = 3, fill = "white", hjust = 0) +
coord_flip() +
facet_wrap(~ sex, scales = "free") +
theme(
axis.title = element_blank()
)
Whenever possible, I try to reshape data and use geom_col rather than try to get lucky with geom_bar. You should be able to play around with different hard-coded values of y in the geom_label call to fix the proper location for your labels based on your formatting and image size/scale.

distance to legend text ggplot

I am trying to get a little more distance between the legend box (indicator) and the legend text. I have a code adapted from this amazing page. Here is my MWE:
library(openxlsx) # for reading in Excel data
library(dplyr) # for data manipulation
library(tidyr) # for data manipulation
library(magrittr) # for easier syntax in one or two areas
library(gridExtra) # for generating some comparison plots
library(ggplot2) # for generating the visualizations
mwedata <- data.frame(Metro=c(rep("Dayton,OH",6)))
mwedata$class <- as.character(c("Lower","Middle","Upper","Lower","Middle","Upper"))
mwedata$year <- as.numeric(c(rep(2000,3),rep(2014,3)))
mwedata$value <- as.numeric(c(0.221,0.580,0.199,0.269,0.527,0.204))
mwedata <- mwedata %>%
mutate(y_label = paste0(round(value*100, 1), "%"))
plot <- ggplot(mwedata, aes(x = class, y = value, fill = factor(year))) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_manual(values = c("#29ABE2", "#217693")) +
geom_text(aes(label = y_label), position = position_dodge(0.9),
vjust = 1.5, color = "white", family = "Georgia")
plot <- plot +
scale_y_continuous(labels = scales::percent) +
scale_x_discrete(labels = c("Lower" = "Lower Class",
"Middle" = "Middle Class", "Upper" = "Upper Class")) +
labs(title = "Distribution of Adults by Income in Dayton, OH",
subtitle = "The percentage of adults in the middle class eroded by 5.3% from 2000 to 2014. Although a small \nfraction of these individuals moved into the upper class (+0.5%), the majority of these middle class \nindividuals moved into the lower income class (+4.8%).",
caption = "Source: Pew Research Center analysis of the \n2000 decennial census and 2014 American \nCommunity Survey (IPUMS)")
plot +
theme_minimal() +
theme(axis.title = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank(),
legend.position = c(1,1), legend.justification = c(1,1),
legend.background = element_blank(),
legend.direction="vertical",
text = element_text(family = "Georgia"),
plot.title = element_text(size = 18, margin = margin(b = 10)),
plot.subtitle = element_text(size = 10, color = "darkslategrey", margin = margin(b = 25)),
plot.caption = element_text(size = 8, margin = margin(t = 10), color = "grey70", hjust = 0),
legend.title = element_blank(),
legend.text.align = 2)
The last line of code legend.text.align is supposed to move the text from the legend coloured boxes, but it only seem to apply for the lower of the two. See the image below. Can anyone help me?
EDIT 1:
I totally forgot to include the defined data.frame. I have now updated the MWE so it really is an WE with this line of code
mwedata <- data.frame(Metro=c(rep("Dayton,OH",6)))
Im sorry for the confusion..
This helps resolve the issue:
Remove legend.title = element_blank() and legend.text.align = 2 from theme()
Add fill = "" to labs()
Curious observation while debugging: using your original code, just changing the font family, e.g. from "Georgia" to "Open Sans", removes the discrepancy in alignment between the two labels in the legend.

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