简体   繁体   中英

Plotting a `geom_rug` on both sides of the plot (left and right) based on `x` value in ggplot2

Problem Statement

Suppose that I have the following function of two variables

f <- function(x, y){
    return(x*y + (x^3)*sin(y))
}

I want to fix two x points, for instance at x=2 and x=3 and then, I want to get, say, 100 standard random normal samples, which I'm going to feed in as y values.

What the data looks like

This is what the data looks like

set.seed(1)
y <- rnorm(100)
df <- data.frame(
    x = c(rep(2, 50), rep(3, 50)), 
    y=c(f(2, head(y, 50)), f(3, tail(y, 50)))
)
head(df)
  x         y
1 2 -5.943113
2 2  1.828189
3 2 -7.605003
4 2 11.188164
5 2  3.247634
6 2 -7.492659

Standard Scatter Plot of the data

df$x <- as.factor(df$x)
ggplot(data=df, aes(x=x, y=y)) + 
    geom_point()

散点图

What I am trying to do

Basically I want to have two geom_rug() one on the left, corresponding to the scatter points for x=2 and one on right, corresponding to the scatter plot for x=3 . I can produce a geom_rug() for all scatter points, as shown below, but I don't know how to have two different

ggplot(data=df, aes(x=x, y=y)) + 
    geom_point(aes(color=x)) + 
    geom_rug()

小地毯

Ideally, I'd like the rug plot on the left to have the same color as the scatter points on x=2 , and the rug plot on the right to have the same color as the scatter points on x=3 .

As I said, I did solve the problem by using

ggplot(data=df, aes(x=x, y=y, color=x)) + 
  geom_point(aes(color=x)) + 
  geom_rug(data=subset(df, x==2), sides="l", aes(y=y)) + 
  geom_rug(data=subset(df, x==3), sides="r")

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