Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition of text to x axis in ggplot2

Here is data:

myd <- data.frame (X1 = rep (c("A0001", "B0002", "C0003", "D0004"), each = 2),
X2 = rep (c(1, 5.3, 8.2, 12.5), each = 2), X3 = rep (c("A", "B"), 4),
 Y = rnorm (8, 5, 2))

Here is plot I could plot:

 require(ggplot2)
 ggplot(myd, aes(x = X2, y = Y, group = X3)) + 
geom_point (aes(col = X3, pch = X3)) + geom_line (aes(col = X3))

I want to the X1 text to corresponding position in x axis in addition to X2 values. Just dry sketch:

enter image description here

How can I do it ? Edit:

Note: Objective is to display continous scale and the texts at X axis same time:

like image 312
fprd Avatar asked Oct 20 '25 01:10

fprd


1 Answers

Create two new layers:

  • geom_rug for the lines on the axis
  • geom_text for the labels - but first create a summary of the required labels

The code:

ruglabels <- unique(myd[, 1:2])

require(ggplot2)
ggplot(myd, aes(x=X2, y=Y)) + 
  geom_point (aes(col = X3, pch = X3, col=X3)) + 
  geom_line (aes(col = X3, col=X3)) +
  geom_rug(sides="b") +
  geom_text(data=ruglabels, aes(x=X2, label=X1, y=2))

enter image description here

like image 101
Andrie Avatar answered Oct 22 '25 03:10

Andrie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!