【发布时间】:2019-03-08 11:43:10
【问题描述】:
我有一个时间序列数据,其中我在 y 轴 DIAG_RATE_65_PLUS 上绘制疾病的诊断率,在 x 轴 NAME 上绘制地理组以进行比较,作为一个简单的条形图。我的时间变量是ACH_DATEyearmon,动画正在循环播放,如标题所示。
df %>% ggplot(aes(reorder(NAME, DIAG_RATE_65_PLUS), DIAG_RATE_65_PLUS)) +
geom_bar(stat = "identity", alpha = 0.66) +
labs(title='{closest_state}') +
theme(plot.title = element_text(hjust = 1, size = 22),
axis.text.x=element_blank()) +
transition_states(ACH_DATEyearmon, transition_length = 1, state_length = 1) +
ease_aes('linear')
我重新排序了NAME,所以它的排名是DIAG_RATE_65_PLUS。
gganimate 产生了什么:
我现在有两个问题:
1) gganimate 如何准确地重新排序数据?有一些总体上的一般重新排序,但每个月都没有框架,其中组由DIAG_RATE_65_PLUS 从最小到最大完美排序。理想情况下,我希望完美订购最后一个月的“2018 年 8 月”。之前所有月份的 x 轴都可以基于“2018 年 8 月”的排序 NAME。
2) gganimate 中是否有一个选项可以让组在条形图中每个月“转移”到正确的排名?
我的评论查询图:
https://i.stack.imgur.com/s2UPw.gif https://i.stack.imgur.com/Z1wfd.gif
@JonSpring
df %>%
ggplot(aes(ordering, group = NAME)) +
geom_tile(aes(y = DIAG_RATE_65_PLUS/2,
height = DIAG_RATE_65_PLUS,
width = 0.9), alpha = 0.9, fill = "gray60") +
geom_hline(yintercept = (2/3)*25, linetype="dotdash") +
# text in x-axis (requires clip = "off" in coord_cartesian)
geom_text(aes(y = 0, label = NAME), hjust = 2) + ## trying different hjust values
theme(plot.title = element_text(hjust = 1, size = 22),
axis.ticks.y = element_blank(), ## axis.ticks.y shows the ticks on the flipped x-axis (the now metric), and hides the ticks from the geog layer
axis.text.y = element_blank()) + ## axis.text.y shows the scale on the flipped x-axis (the now metric), and hides the placeholder "ordered" numbers from the geog layer
coord_cartesian(clip = "off", expand = FALSE) +
coord_flip() +
labs(title='{closest_state}', x = "") +
transition_states(ACH_DATEyearmon,
transition_length = 2, state_length = 1) +
ease_aes('cubic-in-out')
使用hjust=2,标签不对齐并四处移动。
把上面的代码改成hjust=1
@eipi10
df %>%
ggplot(aes(y=NAME, x=DIAG_RATE_65_PLUS)) +
geom_barh(stat = "identity", alpha = 0.66) +
geom_hline(yintercept=(2/3)*25, linetype = "dotdash") + #geom_vline(xintercept=(2/3)*25) is incompatible, but geom_hline works, but it's not useful for the plot
labs(title='{closest_state}') +
theme(plot.title = element_text(hjust = 1, size = 22)) +
transition_states(ACH_DATEyearmon, transition_length = 1, state_length = 50) +
view_follow(fixed_x=TRUE) +
ease_aes('linear')
【问题讨论】:
-
您可以发布您的实际数据样本吗?我们可能会建议动画条形图的替代方案,以更好地处理您的数据。
-
@eipi10 您生成的 df 几乎完美地再现了我正在使用的 df,但我已将一小部分数据粘贴到 pastebin here。在您的最后一次编辑中,有没有办法合并
geom_vline?它似乎与ggstancegeoms 不兼容,但geom_hline出于某种原因有效,但对我的情节没有用。在我的问题中添加了代码。 -
为右对齐标签添加一些间距的一个技巧是使用
hjust = 1并将标签更改为aes(label = paste(country, " "))以便它们右对齐但有额外的空格。hjust > 1似乎有一个错误。在这里查看答案:stackoverflow.com/questions/53162821/…
标签: r animation ggplot2 dplyr gganimate