Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 - Axis Aesthetics

Tags:

r

ggplot2

It is possible in ggplot2 to draw that second "axis" label correlating the percentage of values from X and Y.

enter image description here

Edit:

I have a data.frame with two vars, both related and in percentage. I want to show the evolution of V1 related to V2; for example, how much percentage of V2 do i need to get 20% of V1 (and vice-versa).

V1   V2
0    0
0.03 0.0005
0.10 0.0015
0.13 0.0020
....
1    1

Now my problem is how can i do that inner axis on X and Y, showing the relation between X and Y percentages. Also how can I set ggplot to use (0,0) as the intercept of the x and y axis?

like image 870
Barata Avatar asked Apr 21 '11 19:04

Barata


1 Answers

You could build up this graph from layer to layer (with geom_rect and geom_text) easily with ggplot2. Not a shiny solution, but you could get the picture by:

Generate some data to be used on the plot:

df <- data.frame(A=sort(runif(20)), B=sort(runif(20)))
df <- rbind(df, c(1,1))

Generate a modified version of the above data table to be plotted as "inner" axis (note: I only compute two parts by the median):

df_rect <- data.frame(xmin=c(0, median(df$A), -0.01, -0.01), xmax=c(median(df$A), 1, 0, 0), ymin=c(-0.01, -0.01, 0, median(df$B)), ymax=c(0, 0, median(df$B), 1), color=grey(c(0.7, 0.2)), alpha=c(0.8, 0.4, 0.8, 0.4))

Generate something like that for the plotted text:

df_text <- data.frame(x=c(median(df$A)/2, median(df$A) + (1-median(df$A))/2, 0.05, 0.05), y=c(0.02, 0.02, median(df$B)/2, median(df$B) + (1-median(df$B))/2), label=rep('50%', 4))

And at last plot all:

ggplot(df, aes(A, B)) + geom_point() +
    geom_line() +
    geom_rect(data=df_rect, aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax, fill=color, alpha=alpha), inherit.aes = FALSE) + scale_fill_grey() +
    geom_text(data=df_text, aes(x=x, y=y, label=label), inherit.aes = FALSE) + 
    theme_bw() + scale_y_continuous(limits=c(-0.01, 1), formatter='percent') + scale_x_continuous(limits=c(-0.01, 1), formatter='percent') + opts(legend.position="none")

Where geom_point points the given values and geom_line connects all (as I saw in your example image). geom_rect with all parameters draws the grey "inner axis" and geom_text does the text part. You will have to play with the generated (input) data frames (in the above example: df_rext and df_text) to get your desired data for these. theme_bw stands for black and white theme and the two scale_continous option stands for setting the limits between 0 and 1 and also setting the percent formatter.

Which results in: sample plot

I hope you will be able to customize and upgrade this little example to your needs!

like image 198
daroczig Avatar answered Oct 23 '22 05:10

daroczig