Reputation: 437
First question.
I am plotting a scatterplot with ggplot 2 and I would like to add to the datapoint labels, the coordinate of x and y, like this:
Second
Viscosity: 2
Time: 60
Is it possible to achieve something similar?
Second question.
The label position is adjusted with reference of the center. Therefore if I have labels with different size I obtain a differen positioning (line in the following image); is it possible to refer the position (with nudge_x
and nudge_y
or similar) from the left side of the label and not the center?
Below you can find the whole script.
Lamination <- data.frame("Product" = c("First", "second", "Very long word to move 1", "Very long word to move 2", "Third"), "Vix" = c(1.25,2.10,2.99,4.05,5.55), "OT" = c(30,60,90,120,135))
attach(Lamination)
library(ggplot2)
library(readxl)
attach(Lamination)
row.names(Lamination) <- Product
library(ggplot2)
library(ggrepel)
nbaplot <- ggplot(Lamination, aes(x= OT, y = Vix)) + geom_point(color = "red", size = 2) + ggtitle("Product Range") + theme(plot.title = element_text(hjust = 0.5)) + xlab("Time (min)") + ylab("Viscosity")
nbaplot
nbaplot <- nbaplot + geom_text(
label=rownames(Lamination),
nudge_x = 3.5, nudge_y = 0.0,
check_overlap = T
)
nbaplot
Thank you for any eventual reply!!
Upvotes: 0
Views: 39
Reputation: 906
You can use paste
to combine things you want to display in your text and you can use ggrepel
package for nicer alignments of text labels
library(tidyverse)
library(ggrepel)
Lamination <- data.frame("Product" = c("First", "second", "Very long word to move 1", "Very long word to move 2", "Third"), "Vix" = c(1.25,2.10,2.99,4.05,5.55), "OT" = c(30,60,90,120,135))
ggplot(Lamination, aes(x= OT, y = Vix)) +
geom_point(color = "red", size = 2) +
ggtitle("Product Range") +
theme(plot.title = element_text(hjust = 0.5)) +
xlab("Time (min)") +
ylab("Viscosity") +
geom_text_repel(aes(label = paste0(Product, "\n", "Viscosity:", Vix, "\n", "Time:", OT)))
Created on 2021-02-12 by the reprex package (v0.3.0)
Upvotes: 1