我在 R 中撰寫了以下程序:
從名為“giraffe”資料的資料框開始
抽取此資料的 30% 并將其標記為“樣本”
為該資料創建一個直方圖,并將該直方圖“采樣”的區域著色為一種顏色,其他行則為另一種顏色
重復此程序 100 次并制作此程序的影片
library(ggplot2) library(dplyr) library(gganimate) giraffe_data <- data.frame( a = abs(rnorm(1000,17,10)), b = abs(rnorm(1000,17,10))) results <- list() for( i in 1:100) { giraffe_data_i <- giraffe_data a_i <- c("sample", "not_sampled") aa_i <- as.factor(sample(a_i, 1000, replace=TRUE, prob=c(0.3, 0.7))) giraffe_data_i $col = cut(giraffe_data_i$a, c(-Inf, 17, Inf)) giraffe_data_i$sample <- aa_i giraffe_data_i$iteration <- i 1 results[[i]] <- giraffe_data_i } results results_df <- do.call(rbind.data.frame, results) animate( ggplot(results_df, aes(x=a, fill = col)) geom_histogram(binwidth=1) scale_fill_manual(breaks = levels(results_df$col), values = c('blue', 'red')) transition_states(iteration, state_length = 0.2) labs(title = "Group: {closest_state}"), fps = 25)

但出于某種原因,此圖不會更改影片中的顏色。
有人可以告訴我如何解決這個問題嗎?
謝謝
注意:我能夠使用以下代碼更改顏色:
animate(
ggplot(results_df, aes(x=a, color = sample))
geom_histogram(fill="white", position="dodge")
transition_states(iteration, state_length = 0.2)
labs(title = "Group: {closest_state}"),
fps = 5)

但這將兩種顏色顯示為兩個單獨的“組”。我希望只有一個“組”,但在這個“組”中有不同的顏色。有人可以告訴我如何解決這個問題嗎?
謝謝
uj5u.com熱心網友回復:
有時我發現在 gganimate 上游進行資料轉換更容易。因此,這里有一種對資料進行分箱并為每次迭代計數的方法,然后將其繪制為普通列幾何圖形。
library(tidyverse); library(gganimate)
# bins of width 2
bin_wid = 2
results_df_bins <- results_df %>%
# "col" is set at 17 but my bins are at even #s, so to align
# bins with that I offset by 1
mutate(a_bin = floor((a 1)/ bin_wid)*bin_wid) %>%
count(a_bin, col, sample, iteration) %>%
mutate(sample = fct_rev(sample)) # put "sample" first
animate(
ggplot(results_df_bins, aes(x=a_bin, y = n, fill = sample))
geom_col(position = position_stack(reverse = TRUE))
transition_states(iteration, state_length = 0.2)
labs(title = "Group: {closest_state}"),
fps = 25, nframes = 500, height = 300)

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315874.html
下一篇:在R中著色直方圖
