R语言动画条形图显示日期后出现异常字符问题求助
问题:动画条形图日期后出现异常字符
数据集
> dput(data2) structure(list(Date = structure(c(1651795200, 1651795200, 1652400000, 1652400000, 1653004800, 1653004800, 1653609600, 1653609600, 1654214400, 1654214400), tzone = "UTC", class = c("POSIXct", "POSIXt")), Country = c("MYR", "JPY", "MYR", "JPY", "MYR", "JPY", "MYR", "JPY", "MYR", "JPY"), Value = c(-4.58032749341578, -11.8566176470588, -5.27883238229476, -10.9425785482124, -5.06949191159718, -10.00938379731, -4.84618722451869, -9.46424356856266, -5.06949191159718, -12.0721271393643)), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -10L))
我的代码
plot1 <- ggplot(data2, aes(x=reorder(Country, -Value), y=Value, fill=Country)) + geom_bar(stat='identity') plot1 + coord_flip() + transition_states(Date, transition_length = 2,state_length = 1, wrap = FALSE) + geom_text(x=1 ,y=-10, family="Times",aes(label=as.character(Date)),size=6, color ="blue") + xlab("Country")
问题
生成的动画条形图整体效果正常,但日期文本后出现了异常字符(类似时区标识的多余符号)。
解决方案
问题根源是直接将POSIXct类型的Date转为字符时,会自动带上时区标记(比如UTC),导致显示异常。可以用format()函数格式化日期,指定所需格式并剔除多余标识:
修改geom_text中的label参数:
geom_text(x=1 ,y=-10, family="Times",aes(label=format(Date, "%Y-%m-%d")),size=6, color ="blue")
你可以根据需求调整format()内的格式字符串,比如"%Y/%m/%d"或"%b %d, %Y"等,这样就能得到干净的日期文本,不会出现多余字符。
内容的提问来源于stack exchange,提问作者kaix
相关产品推荐
相关产品推荐

