I need to write some text at my shared labels.
I have 4 subplots in my plot and they share the same label axis, so I would like to put some annotation at the Y label (and X label too, but the x label I manage excluding the x labels from all plots except from the last one).
I've tried the annotate function but nothing seems to change.
a <- ggarrange(pet, a63, a64, a65,
labels = c(" Polietileno Tereftalato (PET)", "Amostra 63",
"Amostra 64", "Amostra 65"),
ncol = 1, nrow = 4, label.x=0.18, label.y= 1, align ="v",
vjust=2, hjust=0.2,
legend = "bottom")
a + annotate("text", x = 0, y = 25, label ="Absorbância")
a
Related
I am trying to plot a lollipop chart with 5 groups and repeated elements in those groups. If all elements have different names it works as expected:
Intended behavior:
The problem is that I want to plot only 5 algorithms in different groups, and when I actually name them from Algorithm 1-5 this happens with the plot:
Unexpected behavior:
This is my snippet that produces the correct behavior of the lollipop chart (except for the wrong labels):
library(ggpubr)
# Create dataset
data <- data.frame(
algorithm=paste( "Algorithm ", seq(1,25), sep=""),
category=as.factor(c( rep('A', 5), rep('B', 5), rep('C', 5), rep('D', 5), rep('E', 5))),
metric=c(rep(rev(96:100), 5))
)
ggdotchart(data, x = "algorithm", y = "metric",
color = "category", # Color by groups
palette = c("#264653", "#2a9d8f", "#e9c46a", "#f4a261", "#e76f51"), # Custom color palette
sorting = "descending", # Sort value in descending order
add = "segments", # Add segments from y = 0 to dots
rotate = TRUE, # Rotate vertically
group = "category", # Order by groups
dot.size = 7, # Large dot size
label = round(data$metric), # Add mpg values as dot labels
font.label = list(color = "white", size = 8,
vjust = 0.5), # Adjust label parameters
ggtheme = theme_pubr() # ggplot2 theme
) +
labs(y = "Metric (%)", color="")
This is the new data snippet that causes this behavior:
# Create dataset
data <- data.frame(
algorithm=rep(paste( "Algorithm ", seq(1,5), sep=""), 5),
category=as.factor(c( rep('A', 5), rep('B', 5), rep('C', 5), rep('D', 5), rep('E', 5))),
metric=c(rep(rev(96:100), 5))
)
How can I possibly solve this issue?
Once produced, we can edit this like any other ggplot object. We can use scale_x_discrete() to manipulate the axis labels, which avoids any confusion with the original plot definition and construction under the hood of ggdotchart(). Using your first plot as p, we can do:
alg_labels <- rep(paste( "Algorithm ", seq(1,5), sep=""), 5)
p +
scale_x_discrete(
labels = alg_labels
)
I want to create a figure where for various reasons I need to specify the axis labels myself. But when I specify my labels (some have one digit, some two digits) R suppresses every other two-digit label because it decides there isn't enough room to show them all, but it leaves all of the one-digit labels, leaving the axis looking lopsided.
Is there a way to suppress labels consistently across the whole axis, based on whether any of them need to be skipped? Note: I have a lot of plots with varying scales, so I was looking for something I could use for all of them - I don't want to render all the labels for every plot, or to skip every other label in every plot. Suppressing labels will be desirable for some plots and not for others. I just want to skip every other label consistently, if that's what R chooses to do for the particular plot.
(Here is an example figure of what I mean. What I want is for the "6%" label to also be suppressed in the x axis.)
Example code:
library(labeling)
df <- data.frame("estimate" = c(9.81, 14.29, 12.94),
"lower" = c(4.54, 6.25, 5.12),
"upper" = c(12.85, 20.12, 15.84))
ticks <- extended(min(df$lower), max(df$upper), m = 5, only.loose = TRUE,
Q=c(2, 5, 10))
png("examplePlot.png", width = 1200, height = 900, pointsize = 10, res = 300)
bars <- barplot(df$estimate, horiz = TRUE, col = "white", border = NA,
xlim = c(min(ticks), max(ticks)), xaxt = "n", main = "Example")
arrows(df$lower, bars, df$upper, bars, code = 3, angle = 90, length = 0.03)
points(df$estimate, bars, pch = 20)
tickLabels <- paste(ticks, "%", sep = "")
axis(1, at=ticks, labels = tickLabels, cex.axis=1)
axis(2, at = bars, labels = c("c", "b", "a"), lwd = 0, las = 2)
dev.off()
This depends on the size of the plot, so you'll have to plot each label separately:
axis(1, lwd.ticks = 1, labels = FALSE, at = ticks) # plot line and ticks
i <- seq(1,length(ticks),2) # which labels to plot
for(ii in i)
axis(1, at = ticks[ii], labels = tickLabels[ii], cex.axis = 1, lwd = 0)
I was wondering if I could shift the non-numeric values (e.g., "Trivial" see R code below) up on my axis on side 4 such that each non-numeric value be exactly positioned between the current tickmarks (I need to keep the current tickmarks) on this particular axis?
Note: you see I have placed " " for the highest non-numeric axis value, this is because I don't need it (may be there is way that " " could be deleted).
Here is the R code:
curve(dnorm(x),-3,3,bty="n")
axis(side=4,at = c(0,.1, .2, .3,.4),labels = c("Trivial", "Anecdotal", "Substantial","Strong", " "),las=1)
If you want them exactly between the tick marks, it may be easiest to put specify their positions exactly with a second call to axis to plot the labels.
curve(dnorm(x), -3, 3, bty = "n")
axis(side = 4, at = c(0, .1, .2, .3, .4),
labels = FALSE) # don't generate labels
axis(side = 4,
at = c(0.05, 0.15, 0.25, 0.35), # put the labels half-way between
labels = c("Trivial", "Anecdotal", "Substantial","Strong"),
tick = FALSE, # don't plot the tick marks
las = 1)
I use ggplot to make most of my graphics. These can be single panels, or faceted. To make it easier to track revisions, I would like to generate a small label in the corner of the plot that includes some text.
In pseudo code, I am looking for something like this:
# generate the initial plot
p <- ggplot()
# add the label
p + someAnnotationFunction(label = "Version 1.0", x = 1, y = 0,
hjust = "right", vjust = "bottom" )
# print
print(p)
Or: plot my label nestled in the lower right corner of my figure without messing up the existing ggplot graphics.
So far I'm not having any luck finding a solution. This (very interesting) method doesn't work if you have a full m x n table of facets. Methods using gridExtra tend to mess with the plots too much. So, does anyone have a way to add arbitrary text anywhere on a plot that was generated using ggplot?
Here's a worked solution using gridExtra(), based on Baptiste's comment:
require("ggplot2")
require("gridExtra")
# set our working directory
working.dir <- '/Users/aclifton/Documents/projects/Rcode'
setwd(working.dir)
# create a data frame
df <- data.frame(x =runif(100, 1, 10),
y = runif(100, 1, 10))
#create a plot
p <- ggplot(data = df,
aes(x = x,
y = y)) +
geom_point()
print(p)
We now have our plot, and the trick is adding that label and saving the overall plot using ggsave():
# label to show
sub.label = textGrob("Some kind of label",
gp=gpar(fontsize=6),
x = unit(1, "npc"),
hjust = 1,
vjust = 0)
ggsave(filename=file.path(working.dir,'DemoPlot.png'),
plot = arrangeGrob(p,
sub = sub.label,
clip = FALSE),
scale = 1,
width = 6.5,
height = 3.5,
units = c("in"),
dpi = 300)
Which gives you this:
By making a data frame of your annotations, you can add them on top of your plot using geom_text.
note <- data.frame(xVarName = c(1, 5), yVarName = c(1, 10),
text = c("Version 1.0", "April 26, 2014")
p + geom_text(data = anno, aes(label = text))
"Version 1.0" will show up in the bottom left and "April 26, 2014" will show up in the top right.
By making your notes in a separate dataframe, you can add multiple notes to one graph if desired.
I have a plot with a long label containing an expression and I want to split it on two lines. Adding a "\n" inside the expression the result is not as expected.
ylabel <- expression("A very long label with text and \n
expression"*(alpha+beta) [ij]*" A very long label with text and expression")
curve(x^3 - 3*x, -2, 2, xlab=xlabel)
Any help would be appreciated. Thanks
Here is another solution, relying on atop as did #AndresT in his edit.
Note that we cannot use control character like \n in an expression, which explains why using something like expression(paste("...\n", alpha[i], "....")) would not produce the desired output.
xlabel <- expression(atop("A very long label with text and expression",
paste((alpha+beta)[ij], " A very long label ...")))
curve(x^3 - 3*x, -2, 2, sub=xlabel, xlab="")
Note that I used sub instead of xlab to avoid collision with x tick marks.
plot(1:10, ann = FALSE)
mtext(side = 2, text = "Y Axis", line = 3)
mtext(side = 2, text = "and something extra", line = 2)
For ggplot2:
set.seed(124)
data1 = data.frame(x=1:10,y=rnorm(10,1))
colnames(data1) = c("X", "Y")
theme = theme_set(theme_bw())
# atop is the function to use in order to get two lines
xlab = expression(atop(paste("x Axis"),
"More text"))
ylab = expression(atop(paste("y Axis"),
"Two lines"))
ggplot(data1, aes(x = X, y = Y))+
geom_point(shape = 1, color ="black") +
xlab(xlab) +
ylab(ylab)
#And adjust the margins with opts.
example line in ggplot2:
ylab(expression(atop(paste(italic("Saxifraga tridactylites")),
"individuals per plot")))+