Вертикальный отогональный перевернутый geom_smooth - PullRequest
0 голосов
/ 30 августа 2018

Я хочу построить кучу диаграмм рассеяния для 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 голосов
/ 30 августа 2018

Вы ищете что-то подобное?

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...