简体   繁体   中英

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:

在此输入图像描述

How can I do it ? Edit:

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

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))

在此输入图像描述

If you just want X1 labels and don't want coordinates, you can do something like:

require(ggplot2)


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))

ggplot(myd, aes(x = X2, y = Y, group = X3)) + 
    geom_point (aes(col = X3, pch = X3)) + geom_line (aes(col = X3))+
    scale_x_continuous( breaks = myd$X2, labels = myd$X1)

您的x轴标签图。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM