Number line in ggplot

Hi. I want to draw a number line in ggplot. I don't want all this height in the y axis, and I want the x axis numbers just below the points. How can I change my code? Thank you.

library(ggplot2)
df <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10),
y = c(0,0,0,0,0,0,0,0,0,0),
group = c("A","A","A","B","A","A","A","A","A","A"))
ggplot(df, aes(x = x,y = y, group = group)) +
geom_point(aes(col = group, size=10)) +
scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10)) +
scale_color_manual(values = c("red", "darkblue")) +
theme_classic() +
theme(legend.position="none", axis.text.y=element_blank(), axis.ticks.y=element_blank() )

1 Like

One approach

library(ggplot2)
d <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10),
                 y = c(0,0,0,0,0,0,0,0,0,0),
                 group = c("A","A","A","B","A","A","A","A","A","A"))
ggplot(d, aes(x = x,y = y, group = group, label = x)) +
  geom_point(aes(col = group, size=10)) +
  geom_text(size = 3, color = "white") +
  scale_color_manual(values = c("red", "darkblue")) +
  theme_void() +
  theme(legend.position="none", axis.text.y=element_blank(), axis.ticks.y=element_blank() )

Created on 2023-03-25 with reprex v2.0.2

Thank you Technocrat, but I want less height in the y a xis, and
I want the x axis numbers just below the points.

I was being too cute, to illustrate that there really is no y-axis. What is really needed is to change the aspect of the panel that encompasses the whole plot. I haven't found a way to do that in ggplot2. In the first edition of his book, Hadley had an appendix on using a grob approach with the {grid} package. Depending on your application, using ggsave() with height/width will trim an output image.

library(ggplot2)
d <- data.frame(x = c(1,2,3,4,5,6,7,8,9,10),
                y = c(0,0,0,0,0,0,0,0,0,0),
                group = c("A","A","A","B","A","A","A","A","A","A"))


d |> ggplot(aes(x,y)) +
    geom_point(aes(col = group, size=10)) +
    scale_color_manual(values = c("red", "darkblue")) +
    scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10)) +
    theme(legend.position="none", 
            rect = element_blank(),
            panel.grid = element_blank(),
            axis.title = element_blank(),
            axis.text.y = element_blank(),
            axis.ticks.y=element_blank()
            ) +
    coord_fixed(ratio = 10)

1 Like

OK, this will work for me. Thank you.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.