绘制"水面"在ggplot2中

时间:2017-05-10 16:05:41

标签: r ggplot2 data-visualization

我将一些温度数据绘制为深度的函数。但我希望它对非科学家更友好,并明确表示顶部是水面。有关如何做到这一点的任何想法? (艺术浪潮的奖金!)

到目前为止,以下是一些选项:

library(dplyr); library(ggplot2); library(magrittr);
temperature <- rnorm(30, mean = 20)
depth <- seq(0:29)
df <- data.frame(temperature, depth)

no_surface <- df %>% 
              ggplot(aes(y = depth, x = temperature, colour = temperature)) +
              geom_path(size = 2) + 
              scale_y_reverse() + 
              scale_colour_gradient(low = "blue", high = "red")+
              theme_classic() + 
              theme(legend.position = "none")


flat_surface <- no_surface + geom_hline(yintercept = 0)

wavy_surface <- no_surface + stat_function(fun = function(x)sin(x^1.5), 
                                           size = 1)

2 个答案:

答案 0 :(得分:7)

这个太漂亮了,我眼里含着泪水:

ggplot(df, aes(xmin=1, xmax=10, ymin=-depth+1, ymax=-depth, fill=temperature)) + 
  annotate("text", x=7, y=1.5, label="\u2600", size = 60, color = "orange") + 
  geom_rect() + 
  geom_area(
    aes(x), data.frame(x=c(1,10)), inherit.aes=F, stat="function",
    fun = function(x)abs(sin(2*x))+.2, fill="blue"
  ) + coord_cartesian(ylim=c(-30, 10)) + 
  theme_minimal() + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank()) + 
  labs(x=NULL, y="level")

enter image description here

答案 1 :(得分:1)

我们可以先创建一个water_dat,将您的正弦理念用于波浪:

water_dat <- data.frame(
    x = seq(min(df$temperature), max(df$temperature), length.out = 1000)
) %>%
    mutate(y = sin(x^1.5))

然后我们将使用water_dat以及geom_ribbongeom_line函数中的数据添加一些水。

df %>% 
        ggplot(aes(y = depth, x = temperature, colour = temperature)) +
            geom_ribbon(data = water_dat, aes(x = x, ymax = Inf, ymin = y),
                fill = 'blue', inherit.aes = FALSE, alpha = .3)+
            geom_line(data = water_dat, aes(x = x, y = y),
              inherit.aes = FALSE)+
         geom_path(size = 2) + 
         scale_y_reverse() + 
         scale_colour_gradient(low = "blue", high = "red")+
         theme_classic() + 
         theme(legend.position = "none")