首页 > 解决方案 > gganimate col 图表中的值与原始数据值不同

问题描述

我从动画图表开始并使用 gganimate 包。我发现随着时间的推移生成 col 图表动画时,变量的值会从原始值发生变化。让我给你看一个例子:

Data <- as.data.frame(cbind(c(1,1,1,2,2,2,3,3,3),
                            c("A","B","C","A","B","C","A","B","C"),
                            c(20,10,15,20,20,20,30,25,35)))
colnames(Data) <- c("Time","Object","Value")
Data$Time <- as.integer(Data$Time)
Data$Value <- as.numeric(Data$Value)
Data$Object <- as.character(Data$Object)
p <- ggplot(Data,aes(Object,Value)) +
  stat_identity() +
  geom_col() +
  coord_cartesian(ylim = c(0,40)) +
  transition_time(Time)
p  

得到的图表是这样的:

在此处输入图像描述

在 Y 轴上获得的值介于 1 和 6 之间。似乎原始值 10 对应于 Y 轴上的值 1。15 是 2,20 是 3,依此类推……

有没有办法在图表中保留原始值?

提前致谢

标签: rgganimate

解决方案


1

  1. 当您将因子变量强制转换为数字时,您的数据发生了变化。(请参阅data如何有效定义 data.frame 部分)
  2. 你错过了一个position = "identity"让你的条形图留在同一个地方。我添加了一个fill = Time用于说明。

代码

p <- ggplot(Data, aes(Object, Value, fill = Time)) +
     geom_col(position = "identity") +
     coord_cartesian(ylim = c(0, 40)) +
     transition_time(Time)
p  

数据

Data <- data.frame(Time = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                   Object = c("A", "B", "C", "A", "B", "C", "A", "B", "C"),
                   Value = c(20, 10, 15, 20, 20, 20, 30, 25, 35))

推荐阅读