This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
You can also embed plots, for example:
install.packages(“gganimate”) # 必要なライブラリを読み込む library(tidyverse) library(gganimate) library(gifski)
df <- tibble( 都市 = c(“ニューヨーク”, “ロンドン”, “東京”, “シンガポール”, “シドニー”, “パリ”, “ベルリン”), “1_政治” = c(7, 8, 9, 9, 8, 7, 8), “2_経済” = c(10, 9, 9, 9, 8, 8, 8), “3_安全” = c(6, 7, 9, 10, 9, 6, 8), “4_健康” = c(7, 6, 8, 9, 8, 8, 8), “5_教育” = c(9, 9, 8, 9, 8, 9, 8), “6_環境” = c(5, 6, 7, 9, 9, 7, 9) )
df_long <- df %>% pivot_longer(cols = -都市, names_to = “視点”, values_to = “スコア”) %>% group_by(都市) %>% mutate(累積スコア = cumsum(スコア)) %>% ungroup()
df_long <- df_long %>% group_by(視点) %>% arrange(視点, -累積スコア) %>% mutate(ランキング = row_number()) %>% ungroup()
animated_plot <- ggplot(df_long, aes(x = ランキング, y = 累積スコア, fill = 都市)) + geom_col() + # geom_barからgeom_colに変更して高さを累積スコアに基づかせる geom_text(aes(x = ランキング, y = 0, label = 都市), hjust = 1) + # ラベルを棒の左端に配置 coord_flip() + # ランキングに基づいてグラフを反転 scale_x_reverse() + # ランキングを反転して1位が上に来るようにする labs(title = “都市別累積スコアの変動 - {closest_state}”, x = “ランキング”, y = “累積スコア”) + theme_minimal() + transition_states(視点, transition_length = 2, state_length = 1) + ease_aes(‘cubic-in-out’)
animate(animated_plot, nframes = 100, fps = 10, width = 800, height = 600, renderer = gifski_renderer())
anim_save(“city_ranking_cumulative_dynamic.gif”, animation = last_animation())
Note that the echo = FALSE parameter was added to the
code chunk to prevent printing of the R code that generated the
plot.