垂直正交倒角geom_smooth

时间:2018-08-29 22:16:49

标签: r ggplot2 plot

我想为EDA绘制一堆散点图。我不想第二次绘制每个双变量组合,但我确实想要两个黄土平滑度。

mtcars%>%
  ggplot(aes(x=hp,y=wt)) +
  geom_point(stat="identity", position="jitter", alpha=0.3, size=1)+ 
  geom_density2d(stat="density2d", position="identity") + geom_smooth(color="red") +
  geom_smooth(aes(x=wt,y=hp),color="green")

使天平射出并挤压所有人的斧头。

aplot <- mtcars%>%
  ggplot(aes(x=hp,y=wt)) +
  geom_point(stat="identity", position="jitter", alpha=0.3, size=1)+ 
  geom_density2d(stat="density2d", position="identity") + geom_smooth(color="red")
aplot <- aplot + coord_flip() 
aplot + geom_smooth(color="green")

只需转动图并为黄土着色为绿色即可。

1 个答案:

答案 0 :(得分:1)

您是否正在寻找类似的东西?

plot

您可以使用ggplot为翻转的数据计算绿色平滑线的坐标,然后将其添加到原始图形中。

# original plot
aplot <- mtcars %>%  
  ggplot(aes(x = hp, y = wt)) +
  geom_point(position = "jitter", alpha = 0.3, size = 1) +
  geom_density2d() + # no need to state default parameters explicitly
  geom_smooth(color = "red", fill = "red", alpha = 0.2)

# create a new ggplot object for the flipped version
smooth.y <- mtcars %>%
  ggplot(aes(x = wt, y = hp)) + # note x & y are flipped
  geom_smooth()

# extract the relevant coordinates from smooth.y in two forms:
smooth.y.data <- layer_data(smooth.y) %>%
  select(x, y, ymin, ymax) %>%
  rename(y = x,
         x = y, 
         xmin = ymin, 
         xmax = ymax) %>%
  arrange(y)

smooth.y.data.polygon <- rbind(smooth.y.data %>% select(y, xmin) %>% rename(x = xmin),
                               smooth.y.data %>% select(y, xmax) %>% rename(x = xmax) %>%
                                 arrange(desc(y)))

# add the results back to the original plot
aplot +
  #vertical ribbon
  geom_polygon(data = smooth.y.data.polygon,
               aes(x = x, y = y), inherit.aes = FALSE,
               fill = "green", alpha = 0.2) +
  #vertical line
  geom_path(data = smooth.y.data,
            aes(x = x, y = y), inherit.aes = FALSE, 
            color = "green", size = 1)