简体   繁体   中英

How to plot on two Y axis based on X value in R?

Here is my question, I have a data like this

  A B C D 

a 24 1 2 3 

b 26 2 3 1

c 25 3 1 2

Now I would like to plot A in a Y axis (0 to 30) and B~D in another Y axis (0 to 5) in one graph. Also, I want a, b, c row has a line to link them together (lets say a, b, c represents a mouse ID). Could anyone come up with ideas on how to do it? I prefer using R. Thanks in advance!

# create some data
data = as.data.frame(list(A = c(24,26,25),
                     B = c(1,2,3),
                     C = c(2,3,1),
                     D = c(3,1,2)))

# adjust your margins to allow room for your second axis
par(mar=c(5, 4, 4, 4) + 0.1)
# create your first plot
plot(1:3,data$A,pch = 19,ylab = "1st ylab",xlab="index")

# set par to new so you dont' overwrite your current plot
par(new=T)
# set axes = F, set your ylim and remove your labels
plot(1:3,data$B,ylim = c(0,5), pch = 19, col = 2,
     xlab="", ylab="",axes = F)

# add your points
points(1:3,data$C,pch = 19,col = 3)
points(1:3,data$D, pch = 19,col = 4)

# set the placement for your axis and add text
axis(4, ylim=c(0,5))
mtext("2nd ylab",side=4,line=2.5)

在此处输入图片说明

I greatly prefer using ggplot2 for plotting. Sadly, ggplot2 does not support this for philosophical reasons .

I would like to propose an alternative which uses facets, ie subplots. Note that to be able to plot the data using ggplot2 , we need to change the data structure. We do this using gather from the tidyr package. In addition, I use the programming style as defined in dplyr (which uses piping a lot):

library(ggplot2)
library(dplyr)
library(tidyr)

df = data.frame(A = c(24, 26, 25), B = 1:3, C = c(2, 3, 1), D = c(3, 1, 2))
plot_data = df %>% mutate(x_value = rownames(df)) %>% gather(variable, value, -x_value)
ggplot(plot_data) + geom_line(aes(x = x_value, y = value, group = variable)) + 
                    facet_wrap(~ variable, scales = 'free_y')

在此处输入图片说明

Here, each subplot has it's own y-axis.

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