I have been able add a facet based label, however, how do I make it label as the text:
"Mean = 0.235" instead of just "0.235"
Here's my ggplot, where the important part is geom_text:
ggplot(data = filter(season_melt,(HOUSEHOLD_ID_ANONYMISED %in% c(37218002754,37218032412, 38443537620))), aes(factor(HOUSEHOLD_ID_ANONYMISED), value)) +
geom_boxplot(aes(fill = factor(HOUSEHOLD_ID_ANONYMISED))) +
facet_wrap(~Season) +
theme(text = element_text(size=40), legend.position = "none") +
xlab("Household ID") +
ylab("Usage") +
geom_hline(data = mean_season, aes(yintercept = Mean), size = 1, colour = "blue", linetype = "dashed") +
geom_text(data = mean_season, aes(0,Mean,label = round(Mean,3), vjust = -1, hjust = -0.1), color = "blue", size = 11)
Here's a pic which shows the labels in each facet:
You have (at least) two options.
Create the appropriate character string
# Something like
geom_text(data = mean_season,
aes(0, Mean, label = sprintf('Mean = %0.3f', Mean),
vjust = -1, hjust = -0.1),
color = "blue", size = 11)
# or
geom_text(data = mean_season,
aes(0, Mean, label = paste('Mean = ',round(Mean, 3)),
vjust = -1, hjust = -0.1),
color = "blue", size = 11)
Use parse=TRUE in the call to geom_text. In this case you would need to construct an appropriate expression according to ?plotmath (and ?geom_text)
geom_text(data = mean_season, parse = TRUE
aes(0, Mean, label = paste('Mean ==',round(Mean, 3)),
vjust = -1, hjust = -0.1),
color = "blue", size = 11)
Option 2 will create a "nicer" looking expression when visualized.
Related
I have this data frame :
Raw.Score = c(0,1,2,3,4,5,6,7,8)
Severity = c(-3.56553994,-2.70296933,-1.63969850,-0.81321707,-0.04629182,
0.73721320,1.61278518,2.76647043,3.94804472)
x = data.frame(Raw.Score = Raw.Score, Severity = Severity)
Raw.score are raw numbers from 0 to 8 (let's consider them as the labels of the severity numbers)
Severity are relative numbres that represent the locations of the scores in the diagram
I want to graphically present the results as in the following example using ggplot (the example includes different numbers but I want something similar)
As a fun exercise in ggplot-ing here is one approach to achieve or come close to your desired result.
Raw.Score = c(0,1,2,3,4,5,6,7,8)
Severity = c(-3.56553994,-2.70296933,-1.63969850,-0.81321707,-0.04629182,
0.73721320,1.61278518,2.76647043,3.94804472)
dat <- data.frame(Raw.Score, Severity)
library(ggplot2)
dat_tile <- data.frame(
Severity = seq(-4.1, 4.1, .05)
)
dat_axis <- data.frame(
Severity = seq(-4, 4, 2)
)
tile_height = .15
ymax <- .5
ggplot(dat, aes(y = 0, x = Severity, fill = Severity)) +
# Axis line
geom_hline(yintercept = -tile_height / 2) +
# Colorbar
geom_tile(data = dat_tile, aes(color = Severity), height = tile_height) +
# Sgements connecting top and bottom labels
geom_segment(aes(xend = Severity, yend = -ymax, y = ymax), color = "orange") +
# Axis ticks aka dots
geom_point(data = dat_axis,
y = -tile_height / 2, shape = 21, stroke = 1, fill = "white") +
# ... and labels
geom_text(data = dat_axis, aes(label = Severity),
y = -tile_height / 2 - .1, vjust = 1, fontface = "bold") +
# Bottom labels
geom_label(aes(y = -ymax, label = scales::number(Severity, accuracy = .01))) +
# Top labels
geom_point(aes(y = ymax, color = Severity), size = 8) +
geom_text(aes(y = ymax, label = Raw.Score), fontface = "bold") +
# Colorbar annotations
annotate(geom = "text", fontface = "bold", label = "MILD", color = "black", x = -3.75, y = 0) +
annotate(geom = "text", fontface = "bold", label = "SEVERE", color = "white", x = 3.75, y = 0) +
# Fixing the scales
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(limits = c(-ymax, ymax)) +
# Color gradient
scale_fill_gradient(low = "orange", high = "red", guide = "none") +
scale_color_gradient(low = "orange", high = "red", guide = "none") +
# Get rid of all non-data ink
theme_void() +
# Add some plot margin
theme(plot.margin = rep(unit(10, "pt"), 4)) +
coord_cartesian(clip = "off")
I am trying to add labels to a ggplot object. The labels do not look neat and tidy due to their positioning. I have tried using various geom_label_repel and geom_text_repel options but am not having much luck.
I cannot share the data unfortunately, but I have inserted one of my codes below and a screenshot of one section of the redacted graph. The graph has multiple peaks that need labelling. Each label has 2 lines.
I would like the lines connecting the labels to be directly above each peak on the x axis, then turn at a right angle and the line continue horizontally slightly. I would then like the label to sit on top of this horizontal section of the line.
Some peaks are very close together, so the labels will end up being pushed up the y axis so they are able to stack up neatly.
I hope that description makes sense. I would appreciate it if anyone is able to help.
Thank you!
library(ggplot2)
library(ggrepel)
library(dplyr)
upper_plot <- ggplot() +
geom_point(data = plot_data[which(analysis == "Analysis1"),],
aes(x = rel_pos, y = logged_p, color = as.factor(chr)),
size = 0.25) +
scale_color_manual(values = rep(my_upper_colors, nrow(axis_df))) +
geom_point(data=upper_highlight_pos2_old,
aes(x = rel_pos, y = logged_p),
color= c('grey'),
size=0.75,
pch = 16) +
geom_point(data=upper_labels_old,
aes(x = rel_pos, y = logged_p),
color='dark grey',
size=2,
pch = 18) +
geom_point(data=upper_highlight_pos2_novel,
aes(x = rel_pos, y = logged_p),
color= c('black'),
size=0.75,
pch = 16) +
geom_point(data=upper_labels_novel,
aes(x = rel_pos, y = logged_p),
color='black',
size=2,
pch = 18) +
scale_x_continuous(labels = axis_df$chr,
breaks = axis_df$chr_center,
expand = expansion(mult = 0.01)) +
scale_y_continuous(limits = c(0, maxp),
expand = expansion(mult = c(0.02, 0.06))) +
# geom_hline(yintercept = -log10(1e-5), color = "red", linetype = "dashed",
# size = 0.3) +
geom_hline(yintercept = -log10(5e-8), color = "black", linetype = "dashed",
size = 0.3) +
labs(x = "", y = bquote(atop('GWAS', '-log'[10]*'(p)'))) +
theme_classic() +
theme(legend.position = "none",
axis.title.x = element_blank(),
plot.margin = margin(t=5, b = 5, r=5, l = 10)) +
geom_label_repel(data = upper_labels,
aes(x = rel_pos, y = logged_p, label = label),
ylim = c(maxp / 3, NA),
size = 2,
force_pull = 0,
nudge_x = 0.5,
box.padding = 0.5,
nudge_y = 0.5,
min.segment.length = 0, # draw all lines no matter how short
segment.size = 0.2,
segment.curvature = -0.1,
segment.ncp = 3,
segment.angle = 45,
label.size=NA, #no border/box
fill = NA, #no background
)
This is my current untidy layout...
EDIT:
This is the sort of layout I am after. The lines will need to be flexible and either be right-handed or left-handed depending on space (source: https://www.nature.com/articles/s41588-020-00725-7)
I want to add a legend for the plot, but it doesn't work,
can anyone please help me to see where it went wrong.
this is the code.
ggplot(data = dfNorm1, aes(x = X)) +
geom_col(aes(y = Government_suppliment),
fill = "#0000FF", color = "white", alpha = 0.8) +
geom_smooth(data = subset(dfNorm1,X >= 24), aes(y = Government_suppliment),
method = "lm", se = FALSE, color = "#FF4040",
linetype = "dashed", size = 0.7) +
geom_smooth(data = subset(dfNorm1, X <= 24), aes(y = Government_suppliment),
method = "lm", se = FALSE, color = "#FF4040",
linetype = "dashed", size = 0.7) +
geom_vline(xintercept = 24.5, size = 0.8, alpha = 0.8) +
geom_line(aes(y = Poverty_funds),
color = "#FF0000", size = 1, alpha = 0.7) +
geom_line(aes(y = MLI), color = "#EF3EFF", size = 1,
alpha = 0.8) +
scale_fill_manual(name = "",values = c("bar.label" = "#0000FF")) +
scale_color_manual(name = "", values = c("line.label1" = "#FF0000", "line.label2" = "#EF3EFF",
"line.labeld" = "#FF4040"))
You usually can produce a legend by setting aes(color = column_title) in one of your geom layers. This code doesn't particularly make sense because you are referencing more than one y-axis without creating a second y-axis (a bad habit if you are trying to do so). Is there a way you can post more relevant code or a reproducible example so people can see exactly what you're trying to do?
I am creating a stacked bar chart below using ggplot and I convert it to interactive using ggplotly(). As you can see in the screenshot below the pop up text when I hover over a bar shows as "Name" the correct "Name" of the relative bar-in that case- DCH. I tried to replace that with a name of my choice but then the whole chart breaks down. So basically I would like to know if I can use "Name" in the background in order to display the chart but display another Name instead. The same for all of the 5 bars.
The code chunk which is related with this is:
geom_col(mapping = aes(x = Name, y = count, fill = Class), width = rep(0.9,5),
color = "black", position = position_fill(reverse = T)) +
geom_text(size = 4, position = position_fill(reverse = T, vjust = 0.50), color = "black",
mapping = aes(x = Name, y = count, group = Class, label = round(count))) +
#DATA
Name<-c("DCH","DCH","DCH","DGI","DGI","DGI","LDP","LDP","LDP","RH","RH","RH","TC","TC","TC")
Class<-c("Class1","Class2","Overlap","Class1","Class2","Overlap","Class1","Class2","Overlap","Class1","Class2","Overlap","Class1","Class2","Overlap")
count<-c(2077,1642,460,1971,5708,566,2316,810,221,2124,3601,413,2160,1097,377)
FinalDF<-data.frame(Name, Class,count)
#PLOT
ggplotly(ggplot(data = FinalDF) +
geom_col(mapping = aes(x = Name, y = count, fill = Class), width = rep(0.9,5),
color = "black", position = position_fill(reverse = T)) +
geom_text(size = 4, position = position_fill(reverse = T, vjust = 0.50), color = "black",
mapping = aes(x = Name, y = count, group = Class, label = round(count))) +
annotate('text', size = 5, x = (5+1)/2, y = -0.1, label = c('A'), angle = 90) +
coord_flip() +
scale_fill_manual(values = c('lemonchiffon', 'palegreen3', 'deepskyblue2'),breaks=c("Class1", "Overlap", "Class2"), labels = c(paste("Unique to","DB"), "Overlap", "Unique to Comparison Dataset "),
guide = guide_legend(label.position = 'left', label.hjust = 0, label.vjust = 0.5)) )
The tooltip argument might be in the right direction.
library(sf)
library(plotly)
# Create the stacked bar plot using ggplot()
stackedBarPlot<- ggplot(data = FinalDF) +
geom_col(mapping = aes(x = Name, y = count, fill = Class), width = rep(0.9,5),
color = "black", position = position_fill(reverse = T)) +
geom_text(size = 4, position = position_fill(reverse = T, vjust = 0.50), color = "black",
mapping = aes(x = Name, y = count, group = Class, label = round(count))) +
annotate('text', size = 5, x = (5+1)/2, y = -0.1, label = c('A'), angle = 90) +
coord_flip() +
scale_fill_manual(values = c('lemonchiffon', 'palegreen3', 'deepskyblue2'),breaks=c("Class1", "Overlap", "Class2"), labels = c(paste("Unique to","DB"), "Overlap", "Unique to Comparison Dataset "),
guide = guide_legend(label.position = 'left', label.hjust = 0, label.vjust = 0.5))+
geom_sf(aes(fill=Class,text=paste(Name,"DB")))
stackedBarPlot%>%
ggplotly(tooltip = "text")
I have a data set with 2 factors (MACH & YOU) Id like to produce a BoxPlot using ggplot2 and have the BoxPlot colour split by MACH whilst highlighting certain points (YOU) in a different shape and in Black..?
I can get the plot working but i can't make the (YOU) factor be bigger in terms of shape and make it black...without effecting all other points on the graph.
Ignore the commented lines - I was just playing around with those.
My dataframe x has the form
MEDIAN MACH YOU PROD
34.5 tool1 false ME
33.8 tool1 false ME
32.9 tool2 true ME
30.1 tool2 true ME
33.8 tool2 false.....etc
x<- data.frame(MEDIAN=c(34,32,56,34,45,34,45,33,23), MACH=c("t1","t1","t1","t2","t2","t2","t1","t1","t2"), YOU=c("false","false","false","false","true","true","true","false","false"), PROD="U","U","U","U","U","U","U","U","U")
ggplot(data=x,aes(MACH,MEDIAN ))+
geom_boxplot(fill = "white", colour = "blue")+
theme(panel.grid.minor = element_line(colour = "grey"), plot.title = element_text(size = rel(0.8)),axis.text.x = element_text(angle=90, vjust=1), strip.text.x = element_text(size = 8, colour = "black", face = "bold")) +
#geom_abline(colour = "grey80")+
#geom_point(shape = factor(YOURLOTS)), size = 3) +
#geom_hline(yintercept=x$TARG_AVG,colour = "green")+
#geom_hline(yintercept=x$TARG_MIN,colour = "red")+
#geom_hline(yintercept=x$TARG_MAX,colour = "red")+
geom_point(alpha = 0.6, position = position_jitter(w = 0.05, h = 0.0), aes(colour=factor(MACH),shape = factor(YOU)), size =3)+
facet_wrap(~PROD, scales = "free") +
ggtitle("MyTitle") +
scale_size_area() +
xlab("STAGE HIST EQUIPID")+
ylab("yaxis")
If you want to make the points for YOU of different size, depending on their value, you can add aes(size = factor(YOU)) inside geom_point().
You can choose the range of size of the points adding scale_size_discrete(range = c(3, 6)) to you plot. In this example, the minimum size would be 3 and the maximum value would be 6.
That would be
ggplot(data = x, aes(MACH, MEDIAN)) +
geom_boxplot(fill = "white", aes(color = MACH)) +
geom_point(aes(shape = factor(YOU), size = factor(YOU)), color = "black", alpha = 0.6, position = position_jitter(w = 0.05, h = 0.0)) +
labs(title = "My Title", x = "Stage Hist Equip ID", y = "y-axis") +
scale_size_discrete(range = c(3, 6))
I would solve this by using two subsets and two calls to geom_point():
library(ggplot2)
x <- data.frame(MEDIAN = c(34,32,56,34,45,34,45,33,23),
MACH = c("t1","t1","t1","t2","t2","t2","t1","t1","t2"),
YOU = c("false","false","false","false","true","true","true","false","false"),
PROD = c("U","U","U","U","U","U","U","U","U"))
ggplot(data = x, aes(MACH, MEDIAN)) +
geom_boxplot(fill = "white", colour = "blue") +
geom_point(data = subset(x, YOU != "true"), aes(color = MACH),
size = 8, alpha = 0.6,
position = position_jitter(w = 0.05, h = 0.0)) +
geom_point(data = subset(x, YOU == "true"), aes(shape = YOU),
color = "black", size = 8, alpha = 0.6,
position = position_jitter(w = -0.05, h = 0.0)) +
labs(title = "My Title", x = "Stage Hist Equip ID", y = "y-axis")