Martin Andersen
Martin Andersen

Reputation: 153

Can you add labels under an existing axis?

I am using ggplot2 in r and have made my plot. I would however like to add some intervals, that I have in a .csv file, under my existing x-axis.

Here is an example to show what I would like to plot under my x-axis: http://www.nature.com/nprot/journal/v8/n5/images/nprot.2013.053-F3.jpg Picture "a" has intervals under the x-axis. I have a .csv file with intervals in the format:

Fraction no.; Interval
"1"; [0:2]
"2"; [2:4]

and so on, up to around 80, so I would like them added automatically. I hope it's possible so I won't have to do it manually in another program.

Upvotes: 3

Views: 366

Answers (2)

Martin Andersen
Martin Andersen

Reputation: 153

I chose another solution, using annotate and making an area inside the plot, e.g.:

annotate("rect", xmin = 10, xmax = 30, ymin = -Inf, ymax = Inf, fill = "grey70", alpha = 0.3) +
annotate("text", x = 20, y = -65, color = "black", label = "3-6", size = 3) +
annotate("rect", xmin = 78, xmax = 94, ymin = -Inf, ymax = Inf, fill = "grey70", alpha = 0.3) +
annotate("text", x = 86, y = -65, color = "black", label = "24-39", size = 3)

Resulting in this plot: Plot with areas marked with annotate

Upvotes: 1

maeVeyable
maeVeyable

Reputation: 152

We can use geom_segment from ggplot to draw the intervals in a new figure and regroup your plot with them with grid.arrange() from gridExtra library.

For example, with iris data : I created an histogram :

g <- ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+geom_histogram(stat="identity")

Then with interval data like that :

inter <- data.frame(v1=seq(0,max(iris$Sepal.Length),1.5),v2=seq(1,max(iris$Sepal.Length)+2,1.5))

head(inter)
   v1  v2
1 0.0 1.0
2 1.5 2.5
3 3.0 4.0
4 4.5 5.5
5 6.0 7.0
6 7.5 8.5

I created a new plot with no background and axis :

top <- ggplot(inter,aes(v1,0))+geom_segment(aes(x=v1,y=0,xend=v2,yend=0))+geom_segment(aes(x=v1,xend=v1,y=0,yend=0.5))+geom_segment(aes(x=v2,xend=v2,y=0,yend=0.5))+theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),panel.background = element_blank(),axis.ticks=element_blank(),axis.text=element_blank())+xlab("")+ylab("")

And add it to the previous plot

grid.arrange(g,top,ncol=1,nrow=2,heights=c(6,1))

This is the result :

enter image description here

Upvotes: 4

Related Questions