How to right-justify with hjust - r

from what I have been reading hjust takes a value from 0 to 1. 0 means left justified, 1 means right justified.
As you can see in my example it does not work like this for me. This is my code:
library(ggplot2)
abundance_environment <- read.table('/home/agalvez/data/environmental_data/vanellid/environmental_parameters.csv', sep="\t", header=TRUE)
lineplot9 <- ggplot(abundance_environment, aes( x = abundance_environment$Chlorophyll_A..mg.m..3., y = abundance_environment$log, group = abundance_environment$Depth_Nominal , colour = abundance_environment$Depth_Nominal)) +
geom_point( size =2, shape =16) +
xlab("Chlorophyll A (mg/m³)") + ylab("Relative abundance") + ggtitle("Abundance-Chlorophyll A") +
theme_bw() +
labs(colour = "Depth") +
stat_cor(method = "spearman", size= 3, p.accuracy = 0.001, r.accuracy = 0.001, hjust=1) +
geom_smooth(method= lm, se= FALSE, size= 1)
lineplot9
cor(x= abundance_environment$Chlorophyll_A..mg.m..3., y= abundance_environment$log, method = "spearman", use = "complete.obs")
As you can see, my correlation values appear in the wrong position. How could I solve that?
EDIT:
Result of
stat_cor(label.y.npc="top", label.x.npc = "right", method = "spearman", size= 3, p.accuracy = 0.001, r.accuracy = 0.001)
> dput(head(abundance_environment))
structure(list(OGA_ID = c(20L, 22L, 66L, 75L, 91L, 126L), sample_ID = structure(c(8L,
3L, 4L, 6L, 7L, 5L), .Label = c("TARA_A100001640", "TARA_N000000077",
"TARA_N010000218", "TARA_N010000238", "TARA_N010000586", "TARA_N010000911",
"TARA_N010000955", "TARA_N010000980"), class = "factor"), log = c(-5.57153717588776,
-6.37156046083652, -6.50881538403584, -6.32529538161919, -6.19086429282228,
-6.38251610427271), Chlorophyll_A..mg.m..3. = c(-0.0018, 1.98441,
-0.0081, 2.6546, -0.0018, 0.83187), Depth..m. = c(391L, 5L, 491L,
17L, 391L, 5L), PAR..mol.quanta.m..2.day. = c(0, NA, NA, NA,
0, 14.83323), O2..µmol.kg. = c(271.8744, 353.1935, 227.316,
373.061, 271.8744, 271.064125), NO3..µmol.l. = c(16.017641,
3.880872, 22.810319, NA, 16.017641, 4.467439), Iron_5m...µmol.l. = c(0.000208521,
0.000596423, 0.000596423, 0.001304139, 0.000208521, 0.000426156
), Ammonium_5m...µmol.l. = c(0.035179306, 0.018947516, 0.018947516,
0.002257904, 0.035179306, 0.007189205), Nitrite_5m...µmol.l. = c(0.348001957,
0.152390116, 0.152390116, 0.010750825, 0.348001957, 0.010129768
), Nitrate_5m...µmol.l. = c(2.06166782, 1.684819688, 1.684819688,
4.442976594, 2.06166782, 0.689068984)), row.names = c(NA, 6L), class = "data.frame")

Looks a bit as if you misinterpreted the working of hjust.
hjust=0 will align the label to the right of the label position,
hjust=1 will align the label to the left of the label position.
dat <- data.frame(
x = factor(1),
y = c(3, 2, 1),
hjust = c(0, .5, 1),
label = c("hjust = 0: right-aligned", "hjust = .5: aligned to the middle", "hjust = 1: left-aligned")
)
library(ggplot2)
ggplot(dat, aes(x, y)) +
geom_text(aes(label = label, hjust = hjust))
Created on 2022-09-28 with reprex v2.0.2
And for your example code and data you could use hjust=0 when you place the label on the left and hjust=1 in case you place it on the right:
library(ggplot2)
ggplot(abundance_environment, aes(x = Chlorophyll_A..mg.m..3., y = log, group = Depth..m., colour = Depth..m.)) +
geom_point(size = 2, shape = 16) +
xlab("Chlorophyll A (mg/m³)") +
ylab("Relative abundance") +
ggtitle("Abundance-Chlorophyll A") +
theme_bw() +
labs(colour = "Depth") +
# Placed on the left, aligned to the right = hjust = 0
ggpubr::stat_cor(method = "spearman", size = 3, p.accuracy = 0.001, r.accuracy = 0.001, hjust = 0) +
# Placed on the right, aligned to the left = hjust = 1
ggpubr::stat_cor(label.x.npc = "right", method = "spearman", size = 3, p.accuracy = 0.001, r.accuracy = 0.001, hjust = 1) +
geom_smooth(method = lm, se = FALSE, size = 1)

Related

Adding p value on top of grouped bar plot

This is my data which I'm trying to plot
dput(results)
structure(list(ontology = c("CC", "BP", "MF", "CC", "BP", "MF",
"CC", "BP", "MF"), breadth = structure(c(3L, 3L, 3L, 2L, 2L,
2L, 1L, 1L, 1L), .Label = c("10", "30", "100"), class = "factor"),
enrichment = c(4.09685904270847, 8.04193317540539, 5.5801230522415,
4.52127958016442, 8.9221766387218, 5.68189764335457, 4.25046722366786,
9.49038239297713, 6.75423163834793), p = c(0, 0, 0, 0, 0,
0, 2.09057402562873e-221, 0, 0)), class = "data.frame", row.names = c(NA,
-9L))
My code
results = read.delim("data/GO/LC-GO-enrichment_new.txt") %>%
mutate(breadth = factor(breadth))
p = ggplot(results, aes(x = breadth, y = enrichment, fill = ontology,
color = ontology)) +
geom_col(position = 'dodge', width = 0.8) +
labs(x = "Breadth", y = "Odds ratio") +
scale_fill_manual(values = ryb8[c(1, 5, 8)], name = "Ontology") +
scale_color_manual(values = darken(ryb8[c(1, 5, 8)], 1.3),
name = "Ontology") +
scale_y_log10(expand = c(0.01, 0)) +
sci_theme
p
I get something like this
is there a way the pvalue can be added similar to this
or its done post making the figure manually .
Any help or suggestion would be really helpfu;
You could simply add the p values as a text layer. Note though, that in your data, each bar has a p value, so it's not clear where the groupwise p values are coming from.
library(ggplot2)
ggplot(results, aes(x = breadth, y = enrichment, fill = ontology)) +
geom_col(position = 'dodge', width = 0.8,
aes(color = after_scale(colorspace::darken(fill, 1.3)))) +
geom_text(aes(label = paste("p", scales::pvalue(p)), group = ontology),
vjust = -1, position = position_dodge(width = 0.8)) +
labs(x = "Breadth", y = "Odds ratio", fill = "Ontology") +
scale_fill_manual(values = c("#d63228", "#dff2f8", "#4575b5")) +
scale_y_log10(expand = c(0.05, 0)) +
theme_classic(base_size = 16) +
theme(legend.position = "top")

geom_text - make text black for plot grouped by color

I have a graph grouped by color with values in text above each point. However, I'd like the writing in black as it's difficult to read.
Could I get some help changing the color of the text from geom_text() to black without losing the positioning?
Adding color = "black" to geom_text() messes up the position of the text, but I'm not sure why...
My data:
structure(list(type = c("full", "full", "full", "noadiposity",
"noadiposity", "noadiposity", "nocv", "nocv", "nocv", "nocv2",
"nocv2", "nocv2", "noenergy", "noenergy", "noenergy", "noenergy2",
"noenergy2", "noenergy2"), fi.cat = structure(c(1L, 2L, 3L, 1L,
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("Non-frail",
"Pre-frail", "Frail"), class = "factor"), mean = c(0.0566154812663495,
0.150817937965167, 0.285714285714286, 0.0459153181095795, 0.148380746409361,
0.292192760942761, 0.0550705669171458, 0.147270820014587, 0.288461538461538,
0.0530093023576546, 0.145279762712841, 0.292717236467236, 0.0531040684693624,
0.146793227463497, 0.292499719195777, 0.054311319499867, 0.14824350913368,
0.283745781777278), sd = c(0.0289882935363143, 0.0342654979144937,
0.0393662413936823, 0.0298601819635622, 0.0345078387756546, 0.0422635938212309,
0.0285280200524055, 0.0338893364029561, 0.0430877768970245, 0.0275365612798787,
0.0358119253511248, 0.0415426999110631, 0.0270394224053038, 0.0374836297491701,
0.0384867847822804, 0.0280882098015465, 0.0353023978795509, 0.039235018559239
)), row.names = c(NA, -18L), groups = structure(list(type = c("full",
"noadiposity", "nocv", "nocv2", "noenergy", "noenergy2"), .rows = structure(list(
1:3, 4:6, 7:9, 10:12, 13:15, 16:18), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
The code I used:
library(ggplot2)
ggplot(grouped_mean, aes(x = fi.cat, y = mean, color = type)) +
geom_point(position = position_dodge(0.9), size = 2) +
geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), position = position_dodge(0.9), size = 1, width = 0.2) +
geom_text(aes(label = round(mean, 2)), vjust = -5.5, position = position_dodge(0.9), size = 3) +
labs(x = "FI category", y = "Mean FI score", color = "FI type") +
scale_color_brewer(palette = "Blues") +
theme_minimal()
Using the colour for the points and error bars automatically splits them into groups. If you're assigning the colour manually, you need to specify the groups in the geom_text() i.e:
ggplot(grouped_mean, aes(x = fi.cat, y = mean, color = type)) +
geom_point(position = position_dodge(0.9), size = 2) +
geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), position = position_dodge(0.9), size = 1, width = 0.2) +
# Add grouping and manual colour to geom_text
geom_text(aes(label = round(mean, 2), group=type), colour="black", vjust = -5.5, position = position_dodge(0.9), size = 3) +
labs(x = "FI category", y = "Mean FI score", color = "FI type") +
scale_color_brewer(palette = "Blues") +
theme_minimal()
Here is an approach: Not the best one, but it seems to work!
This approach uses fill aesthetics and assigns the color aesthetics separately to geom_text aesthetics:
library(ggplot2)
ggplot(grouped_mean, aes(x = fi.cat, y = mean, fill=type)) +
geom_point(position = position_dodge(0.9), size = 2) +
geom_errorbar(aes(ymin = mean-sd, ymax = mean+sd), position = position_dodge(0.9), size = 1, width = 0.2) +
geom_text(aes(label = round(mean, 2)), vjust =-11.5, position = position_dodge(0.9), size = 3) +
labs(x = "FI category", y = "Mean FI score", color = "FI type") +
geom_point(aes(color=type), position = position_dodge(0.9), size = 2) +
geom_errorbar(aes(color=type, ymin = mean-sd, ymax = mean+sd), position = position_dodge(0.9), size = 1, width = 0.2) +
scale_color_brewer(palette = "Blues") +
theme_minimal()+
guides(fill = "none")

how to combine 2 images with fixed area in ggplot2 in R

Here is my raw data.
v <-
structure(list(Estimate = c(0.233244696051868, 5.48753303603373,
1.95671969454631, 3.16568487759413, 4.79631204302344, 2.10818637730716,
0.329940200056173, 0.055145498993132, 0.222410032790494), `Std. Error` = c(1.10523192028695,
2.75434167314693, 2.52507525836928, 0.964768253150336, 1.73374160980673,
0.852388938087655, 0.736511882227423, 0.326506324068342, 1.26750100880987
), ID = structure(c(1L, 3L, 2L, 4L, 8L, 5L, 6L, 7L, 9L), .Label = c("CD",
"MFS2", "MFS", "Crop.Nb", "CD:SNC", "MFS:SNC", "CD:MFS", "SNC",
"SNC2"), class = "factor"), group = structure(c(1L, 1L, 1L, 1L,
3L, 2L, 2L, 2L, 3L), .Label = c("crop", "inter", "semi"), class = "factor"),
ES = c(-0.233244696051868, -5.48753303603373, 1.95671969454631,
3.16568487759413, 4.79631204302344, 2.10818637730716, 0.329940200056173,
0.055145498993132, 0.222410032790494)), class = "data.frame", row.names = c(NA,
-9L))
I want to plot 2 images as below:
p1 <- v %>% ggplot(aes(x = factor(ID), y = ES, color = factor(group))) +
geom_hline(yintercept = 0) +
geom_errorbar(aes(ymin = ES - `Std. Error`,ymax = ES + `Std. Error`),
width = 0, lwd = 1.5
)+
coord_flip()+
geom_text(aes(label = ID), nudge_y = .6,nudge_x = .2)+
geom_point(size = 4)+
scale_color_discrete()+
theme(axis.text.y = element_blank()) +
xlab('') + guides(color = FALSE)
(p2 <- arrange(v,desc(group)) %>% ggplot(aes(x = '1', y =Estimate, fill = group )) +
#geom_bar(position = 'fill', stat = 'identity') +
geom_col(position = position_fill(reverse = TRUE)) +
scale_y_continuous(labels = scales::percent, name = "Variance explained")+
theme(legend.position = 'none', axis.title.x = element_blank(), axis.text.x = element_blank()) )
Now I want to combine p2 and p1: I get:
cowplot::plot_grid(p2,p1,nrow = 1, rel_widths = c(0.2,1))
But what I want to achieve the effect as below:
Panel A : I wish the distance between p1 and p2 is less narrow; And red area only has red bars; Green area only has green bars; I wish you can help me to achieve the draft of panel B as below:
To ensure proper alignment, it might be neater to have both parts in the same plot. Also, I don't quite see the need to flip your coordinates here, so I went with a simpler version:
v %>%
# calculate y-axis positions within [0%, 100%] range
arrange(group) %>%
mutate(y = seq(0.5, by = 1, length.out = n())) %>%
mutate(y = y / ceiling(max(y))) %>%
ggplot(aes(y = y, x = ES, label = ID, color = group,
xmin = ES - `Std. Error`, xmax = ES + `Std. Error`)) +
geom_vline(xintercept = 0) +
geom_pointrange(lwd = 1.5, fatten = 2) + # instead of flipped errorbar with 0 width + point
geom_text(nudge_y = 0.05) +
geom_bar(aes(x = -10, fill = group), # change this to shift the bar closer / further away
position = position_fill(reverse = TRUE),
inherit.aes = FALSE) +
scale_y_continuous(name = "Variance explained", labels = scales::percent) +
# actually not necessary to have this line for default palette, but in case
# you want to change that, the `aesthetics = c("colour", "fill")` line saves you from
# having to specify the same palette twice in both colour & fill scales.
scale_color_discrete(aesthetics = c("colour", "fill")) +
theme_minimal() + # or whatever theme you need
theme(legend.position = "none")

Fixing elongated figures next to each other in R

I'm trying to replicate the theme of these graph using ggplot, I searched online for articles and question to show me how to assign these plots the right size and position and also to assign the tight dot shape, and I found few articles that discussed changing position, I tried the following:
d1<-read.csv("./data/games.csv")
p.1<-ggplot(d1, aes(x=cream_rating, y=charcoal_rating)) +
# Map winner on color. Add some transparency in case of overplotting
geom_point(aes(color = winner), alpha = 0.2) +
# Add the cross: Add geom_pints with one variable fixed on its mean
geom_point(aes(x = mean(cream_rating), color = winner), alpha = 0.2) +
geom_point(aes(y = mean(charcoal_rating), color = winner), alpha = 0.2) +
scale_shape_manual(values=c(16, 17)) +
# "draw"s should be dropped and removed from the title
scale_color_manual(values = c(cream = "seagreen4", charcoal = "chocolate3", draw = NA)) +
ggtitle("Rating of Cream vs Charcoal") +
xlab("rating of cream") + ylab("rating of charcoal") + theme_classic() + theme(plot.title = element_text(hjust = 0.5))
I tried the following to place them together:
require(gridExtra)
plot.1<-p.1
plot.2<-ggExtra::ggMarginal(p.1, type = "histogram")
grid.arrange(plot.1, plot.2, ncol=3)
library(cowplot)
theme_set(theme_cowplot())
plot.1<-p.1
plot.2<-ggExtra::ggMarginal(p.1, type = "histogram")
plot_grid(plot.1, plot.2, labels = "AUTO")
cowplot::plot_grid(plot.1, plot.2, labels = "AUTO")
library(magrittr)
library(multipanelfigure)
figure1 <- multi_panel_figure(columns = 2, rows = 1, panel_label_type = "none")
# show the layout
figure1
figure1 %<>%
fill_panel(plot.1, column = 1, row = 1) %<>%
fill_panel(plot.2, column = 2, row = 1) %<>%
figure1
This is my data set structure:
structure(list(rated = c(FALSE, TRUE, TRUE, TRUE, TRUE, FALSE,
TRUE, FALSE, TRUE, TRUE), turns = c(13L, 16L, 61L, 61L, 95L,
5L, 33L, 9L, 66L, 119L), victory_status = structure(c(3L, 4L,
2L, 2L, 2L, 1L, 4L, 4L, 4L, 2L), .Label = c("draw", "mate", "outoftime",
"resign"), class = "factor"), winner = structure(c(2L, 1L, 2L,
2L, 2L, 3L, 2L, 1L, 1L, 2L), .Label = c("charcoal", "cream",
"draw"), class = "factor"), increment_code = structure(c(3L,
7L, 7L, 5L, 6L, 1L, 1L, 4L, 2L, 1L), .Label = c("10+0", "15+0",
"15+2", "15+30", "20+0", "30+3", "5+10"), class = "factor"),
cream_rating = c(1500L, 1322L, 1496L, 1439L, 1523L, 1250L,
1520L, 1413L, 1439L, 1381L), charcoal_rating = c(1191L, 1261L,
1500L, 1454L, 1469L, 1002L, 1423L, 2108L, 1392L, 1209L)), row.names = c(NA,
10L), class = "data.frame")
This is what I want to achieve:
I tried Stefan's suggestion (which was great help) with some modifications:
d1<-read.csv("./data/games.csv")
ggplot(d1, aes(x=cream_rating, y=charcoal_rating)) +
##### Map winner on color. Add some transparency in case of overplotting
geom_point(aes(color = winner), alpha = 0.2) +
##### Add the cross: Add geom_pints with one variable fixed on its mean
geom_point(aes(x = mean(cream_rating), color = winner), alpha = 0.2) +
geom_point(aes(y = mean(charcoal_rating), color = winner), alpha = 0.2) +
scale_shape_manual(values=c(16, 17)) +
##### "draw"s should be dropped and removed from the title
scale_color_manual(values = c(cream = "seagreen4", charcoal = "chocolate3", draw = NA)) +
ggtitle("Rating of Cream vs Charcoal") +
xlab("rating of cream") + ylab("rating of charcoal") + theme_bw() + theme(plot.title = element_text(hjust = 0.5))
I want to filter out "draw" from the plot, also when I change the dot shapes to triangles and circle, they don't seem to be changing, in addition I get this error:
Warning message:
“Removed 950 rows containing missing values (geom_point).”
Warning message:
“Removed 950 rows containing missing values (geom_point).”
Warning message:
“Removed 950 rows containing missing values (geom_point).”
One more thing that I noticed, I get double cross instead of one!
This is my output:
When I try the first code block in this question, I get long distorted figures not square next to each other.
Maybe this fits your need. To glue the three plots together I make use of the cowplot package. The legend is probably still not perfect.
To get only one legend but still a nice alignment of the plots I made the legends for the first and the third plot "transparent" vis guide_legend and theme options
To make all plots the same size I added transparent marginals to the scatter plot
To fix the position and make the plots square I set the same limits for both axes via xlim and ylim and set the aspect ratio to 1 using theme()
library(ggplot2)
library(dplyr)
library(cowplot)
# Add a second draw to the example data to make the density work
d1 <- d1 %>%
add_row(winner = "draw", cream_rating = 1002, charcoal_rating = 1250)
# Get the limits
lims <- c(floor(min(d1$cream_rating, d1$charcoal_rating)), ceiling(max(d1$cream_rating, d1$charcoal_rating)))
p1 <- d1 %>%
ggplot(aes(x=cream_rating, y=charcoal_rating, color = winner, shape = winner)) +
geom_point(alpha = 0.2, na.rm = TRUE) +
scale_color_manual(values = c(cream = "seagreen4", charcoal = "chocolate3", draw = "blue")) +
scale_shape_manual(values = c(cream = 16, charcoal = 17, draw = 15)) +
xlim(lims) +
ylim(lims) +
labs(x = "rating of cream", y = "rating of charcoal") +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5), legend.position = "bottom") +
theme(aspect.ratio = 1)
p1_1 <- p1 +
guides(color = guide_legend(override.aes = list(color = c(NA, NA, NA)))) +
theme(legend.text = element_blank(), legend.title = element_blank())
p1_1 <- ggExtra::ggMarginal(p1_1, type = "histogram",
margins = 'both',
size = 5,
position = "identity",
color = NA,
fill= NA)
p2 <- ggExtra::ggMarginal(p1, type = "histogram",
margins = 'both',
size = 5,
groupColour = TRUE,
groupFill = TRUE,
position = "identity"
)
# Make legend transparent
p1 <- p1 +
guides(color = guide_legend(override.aes = list(color = c(NA, NA, NA)))) +
theme(legend.text = element_blank(), legend.title = element_blank())
p3 <- d1 %>%
ggplot(aes(x=cream_rating, y=charcoal_rating, color = winner, shape = winner)) +
geom_density_2d(na.rm = TRUE) +
geom_point(alpha = 0, show.legend = FALSE) +
scale_color_manual(values = c(cream = "seagreen4", charcoal = "chocolate3", draw = "blue")) +
xlim(lims) +
ylim(lims) +
labs(x = "rating of cream", y = "rating of charcoal") +
theme_classic() +
theme(plot.title = element_text(hjust = 0.5),
legend.position = "bottom") +
theme(aspect.ratio = 1)
# Make legend transparent
p3 <- p3 +
guides(color = guide_legend(override.aes = list(color = c(NA, NA, NA)))) +
theme(legend.text = element_blank(), legend.title = element_blank())
p3 <- ggExtra::ggMarginal(p3, d1, type = "density",
margins = 'both',
size = 5,
groupColour = TRUE,
groupFill = TRUE,
position = "identity"
)
plot_row <- plot_grid(p1_1, p2, p3, nrow = 1)
# now add the title
title <- ggdraw() +
draw_label(
"Rating of Cream vs Charcoal",
fontface = 'bold',
x = 0,
hjust = 0
)
final <- plot_grid(
title, plot_row,
ncol = 1,
# rel_heights values control vertical title margins
rel_heights = c(0.1, 1)
)
final
Note Depending on the width and heigth of your plotting device, fixing the aspect ratio adds some white space at the top and bottom. Depending on your final output you probably have to play a bit around with the width and height (and scale), e.g. using
ggsave("final.png", width = 18, height = 6, units = "cm", scale = 1.5)
gives

How to change the text in the colour legend of ggplot2

I have this code:
ggplot(databoth, aes(withxstep)) +
geom_point(aes(y = withnassoc, colour = "withnassoc"), size = 2.8) +
geom_point(aes(y = withoutnassoc, colour = "withoutnassoc"), size = 1 ) +
labs(colour = "Legend") +
labs(x = "Time") +
labs(y = "N associations")
How do I modify the withnassoc and the withoutnassoc? I would like it to be "With Activities" and "Without activities".
This should answer your question:
ggplot(databoth, aes(withxstep)) +
geom_point(aes(y = withnassoc, colour = "withnassoc"), size = 2.8) +
geom_point(aes(y = withoutnassoc, colour = "withoutnassoc"), size = 1 ) +
labs(colour = "Legend", x = "Time", y = "N associations") +
scale_color_manual(values = c("red", "blue"),
labels = c("With Activities", "Without activities"))
For this example data-set:
exampledata <- structure(list(withxstep = structure(c(4L, 3L, 2L, 1L),
.Label = c("2017-06-27", "2017-06-28", "2017-06-29", "2017-06-30"), class = "factor"),
withnassoc = c(1, 2, 3, 4), withoutnassoc = c(5, 6, 7, 8)), .Names = c("withxstep",
"withnassoc", "withoutnassoc"), class = "data.frame", row.names = c(NA,-4L))
This would be the plot:

Resources