首页 > 解决方案 > R: How can I make scatter points (geom_point) fade by decreasing in size in animation?

问题描述

I am new to R but got attracted by the immediate nice visualization tools.

I am looking for a nice way to fade scatter points by decreasing in size over time. This is my code:

# Reading libraries
library(gganimate)
library(ggplot2)
library("readxl")

# Reading dataframe
df1 <- read_excel("prices.xlsx")

# Create a group-means data set
ag <- aggregate(df1$SpotPriceEUR, list(df1$PriceArea), mean)

# Specifying plot/animation features
p <- ggplot() +
  geom_point(data = df1, aes(x=SpotPriceEUR, y = PriceArea, colour = SpotPriceEUR,size=2),show.legend=FALSE) +
  geom_point(data = ag, aes(x=ag$x, y = ag$Group.1, size = 1, shape=8),color = "blue",show.legend=FALSE) +
  scale_shape_identity() +
  scale_colour_continuous(low = "green", high = "red",guide = "colourbar") +  
  transition_time(Hour) +
  scale_alpha(range = c(0,1)) +
  guides(alpha = F) +
  theme_minimal() +
  labs(title = "Date: {frame_time}",x = "Spot Price [EUR]",y = "Price Area")

# Animate
animate(p)

This is what I got:

enter image description here

Hope you can visualize what I am looking for.

All the best, DW

Bonus: I am also looking for a way to randomly offset the scatter points in y axis.

标签: rggplot2gganimate

解决方案


看看[enter/exit() functions][1]在 gganimate

我想你想要这样的东西:

    p <- ggplot() +
      geom_point(data = df1, aes(x=SpotPriceEUR, y = PriceArea, colour = SpotPriceEUR,size=2),show.legend=FALSE) +
      geom_point(data = ag, aes(x=ag$x, y = ag$Group.1, size = 1, shape=8),color = "blue",show.legend=FALSE) +
      scale_shape_identity() +
      scale_colour_continuous(low = "green", high = "red",guide = "colourbar") +  
      transition_time(Hour) +
      scale_alpha(range = c(0,1)) +
      guides(alpha = F) +
      theme_minimal() +
      labs(title = "Date: {frame_time}",x = "Spot Price [EUR]",y = "Price Area") + 
      exit_fade()

要沿 y 轴添加一些随机变化,您需要使用 geom_jitter()。尝试这个:

p <- ggplot() +
          geom_jitter(data = df1, aes(x=SpotPriceEUR, y = PriceArea, colour = SpotPriceEUR,size=2),show.legend=FALSE, width = 0, height = 0.25) +
          geom_point(data = ag, aes(x=ag$x, y = ag$Group.1, size = 1, shape=8),color = "blue",show.legend=FALSE) +
          scale_shape_identity() +
          scale_colour_continuous(low = "green", high = "red",guide = "colourbar") +  
          transition_time(Hour) +
          scale_alpha(range = c(0,1)) +
          guides(alpha = F) +
          theme_minimal() +
          labs(title = "Date: {frame_time}",x = "Spot Price [EUR]",y = "Price Area") + 
          exit_fade()

您可能必须使用 geom_jitter 中的宽度/高度参数才能获得您想要的准确方式。


推荐阅读